Feature: add per-device owner bindings to the web console
Web 控制台此前所有 admin 角色用户共享全部设备。新增设备级归属:内置 admin 把设备绑定给一个用户名后,该设备对其他 admin/viewer 不可见不可控,只有 owner 与内置 admin 可见可控。 - 新增 device_acl.json(与 users.json 同目录,YAMA_DEVICE_ACL_FILE 可覆盖), 原子写、启动加载;文件损坏拒绝启动,避免私人设备变成公共。 - 可见性:内置 admin 全部;未绑定设备仅 admin 角色;绑定设备仅 owner。 覆盖 get_devices、/api/devices、屏幕墙,以及 connect/term_open/mouse/key/ clipboard/keyframe/rdp_reset 全部控制通道;device_update 也只推给可见者。 - 只有内置 admin(用户名 admin + role admin)能 bind/unbind;admin 角色保留 建用户、删设备、审计等既有功能。删设备清绑定。 - 审计日志也按归属过滤:非内置 admin 只能看到公共设备和自己绑定设备的记录 (device_id / device / devices 三种写法都识别);auditquery 增 DeviceAllowed 钩子,ACL 提供 Owner 快照,避免扫描时逐条加锁。 - 删用户会解绑其设备;但账号名下有绑定设备时只有内置 admin 能删,其他 admin 删除会把设备释放到公共池,属于越权。解绑在删除前完成,解绑失败中止删除; 删除失败时回滚绑定。 - 绑定/解绑后立即重新校验在线会话:失去权限的屏幕/终端会话被断开。 - 本地用户名禁止 '@'(保留给 SSO 邮箱);本地密码登录拒绝 '@' 用户名, SSO 拒绝名为 admin 的身份,避免绕过超级管理员判定。 - 前端:superadmin 卡片显示 owner、绑定按钮和弹窗(本地用户 datalist + SSO 邮箱自由输入);deviceAcl 能力位由服务端挑战下发,C++ 端无此位不显示; 设备 ID 经 jsAttr 转义后再进 onclick,修掉存储型 XSS。 验证:go build/test/vet 全绿;新增 ACL 持久化、可见性矩阵、控制通道拒绝、 绑定/解绑会话重校验、device_update 不泄露、分组过滤、删用户解绑与越权拒绝、 审计按归属过滤等测试;本地起 Go 服务 + WebSocket 探针验证 challenge、绑定、 非 superadmin 拒绝、解绑。 Model: deepseek-flash Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
db148c4a69
commit
46434b46d0
16 files changed
+1716
-30
No files matched your search
@@ -50,6 +50,12 @@ type Query struct {
|
||||
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
|
||||
WarnOnly bool `json:"warn_only"` // only level=warn records
|
||||
|
||||
// DeviceAllowed, when non-nil, drops records that carry a device_id the
|
||||
// predicate rejects. The MCP endpoint uses it to hide devices bound to a
|
||||
// web user; the web audit page leaves it nil. Not serialisable: it is a
|
||||
// server-side policy hook, not a client filter.
|
||||
DeviceAllowed func(deviceID string) bool `json:"-"`
|
||||
|
||||
// EventContains is a case-insensitive substring match on the event column.
|
||||
// The web UI uses Event's exact/prefix forms; the MCP get_audit_log tool
|
||||
// exposes a "type contains" filter, which maps here.
|
||||
@@ -219,6 +225,13 @@ func recordMatches(rec map[string]any, line string, q Query, from time.Time, has
|
||||
if q.DeviceID != "" && StringField(rec, "device_id") != q.DeviceID {
|
||||
return false
|
||||
}
|
||||
if q.DeviceAllowed != nil {
|
||||
for _, id := range RecordDeviceIDs(rec) {
|
||||
if !q.DeviceAllowed(id) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
if q.WarnOnly && StringField(rec, "level") != "warn" {
|
||||
return false
|
||||
}
|
||||
@@ -256,6 +269,39 @@ func eventFilterMatches(filter, event string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// RecordDeviceIDs returns every device identifier an audit record names.
|
||||
// Producers spell the target differently: web remote-control events use
|
||||
// device_id, MCP tool calls use device, and admin bind/unbind records use a
|
||||
// devices array. A device record written by the MCP audit path uses "-" for
|
||||
// "no device"; that sentinel is not an id.
|
||||
func RecordDeviceIDs(rec map[string]any) []string {
|
||||
var ids []string
|
||||
add := func(v any) {
|
||||
s, ok := v.(string)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" || s == "-" {
|
||||
return
|
||||
}
|
||||
ids = append(ids, s)
|
||||
}
|
||||
add(rec["device_id"])
|
||||
add(rec["device"])
|
||||
switch list := rec["devices"].(type) {
|
||||
case []any:
|
||||
for _, item := range list {
|
||||
add(item)
|
||||
}
|
||||
case []string:
|
||||
for _, item := range list {
|
||||
add(item)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// StringField returns rec[key] when it is a string, else "".
|
||||
func StringField(rec map[string]any, key string) string {
|
||||
s, _ := rec[key].(string)
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
@@ -1173,6 +1174,20 @@ func main() {
|
||||
log.Warn("Failed to load %s: %v (continuing with admin only)", usersFile, err)
|
||||
}
|
||||
|
||||
// Per-device owner bindings live next to users.json. A malformed file is
|
||||
// fatal: silently starting with an empty table would make every private
|
||||
// device public to all admin-role users.
|
||||
aclFile := os.Getenv("YAMA_DEVICE_ACL_FILE")
|
||||
if aclFile == "" {
|
||||
aclFile = filepath.Join(filepath.Dir(usersFile), "device_acl.json")
|
||||
rememberDefault("YAMA_DEVICE_ACL_FILE", aclFile)
|
||||
}
|
||||
deviceACL := web.NewDeviceACL(aclFile)
|
||||
if err := deviceACL.Load(); err != nil {
|
||||
log.Fatal("Failed to load device ACL: %v", err)
|
||||
}
|
||||
log.Info("Device ACL loaded from %s (%d binding(s))", aclFile, len(deviceACL.Snapshot()))
|
||||
|
||||
// TCP authorization (TOKEN_AUTH) brute-force throttle. Keyed by source IP
|
||||
// (the real TCP peer — there is no X-Forwarded-For on the device port).
|
||||
// Generous enough that a NAT office whose devices all re-auth at once is
|
||||
@@ -1366,6 +1381,7 @@ func main() {
|
||||
BasePath: basePath,
|
||||
BrandName: brandName,
|
||||
SSO: ssoDetector,
|
||||
DeviceACL: deviceACL,
|
||||
}
|
||||
|
||||
// Start HTTP server for web UI. Hub gives it read-only access to the
|
||||
|
||||
@@ -32,10 +32,12 @@ const (
|
||||
auditClipGet = "remote.clipboard.get"
|
||||
auditRdpReset = "remote.rdp_reset"
|
||||
|
||||
auditUserCreate = "admin.user.create"
|
||||
auditUserDelete = "admin.user.delete"
|
||||
auditDeviceAdmin = "admin.device.delete"
|
||||
auditQuery = "admin.audit.query"
|
||||
auditUserCreate = "admin.user.create"
|
||||
auditUserDelete = "admin.user.delete"
|
||||
auditDeviceAdmin = "admin.device.delete"
|
||||
auditDeviceBind = "admin.device.bind"
|
||||
auditDeviceUnbind = "admin.device.unbind"
|
||||
auditQuery = "admin.audit.query"
|
||||
)
|
||||
|
||||
// audit emits one audit record for a WebSocket client. Identity fields are
|
||||
|
||||
@@ -32,6 +32,19 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
||||
in.Limit = auditquery.ClampLimit(in.Limit, auditQueryMaxLimit)
|
||||
in.Offset = auditquery.ClampOffset(in.Offset)
|
||||
|
||||
// The audit trail is another visibility channel for devices. An admin-role
|
||||
// user may see public devices and their own, but not another user's bound
|
||||
// devices; the superadmin sees everything. One owner snapshot per query
|
||||
// keeps the scanner off the ACL lock per record.
|
||||
if h.acl != nil && !c.isSuperAdmin() {
|
||||
owners := h.acl.Owners()
|
||||
user := c.user
|
||||
in.DeviceAllowed = func(deviceID string) bool {
|
||||
owner := owners[deviceID]
|
||||
return owner == "" || owner == user
|
||||
}
|
||||
}
|
||||
|
||||
path := h.log.AuditPath()
|
||||
if path == "" {
|
||||
h.audit(c, true, auditQuery, map[string]any{
|
||||
|
||||
@@ -100,6 +100,75 @@ func TestQueryAuditHandlerReturnsEvents(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// An admin-role user may read public-device audit records and their own, but
|
||||
// not records naming another user's bound device. The superadmin sees all.
|
||||
func TestQueryAuditHandlerFiltersBoundDevices(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
lg := logger.New(logger.Config{
|
||||
Level: logger.LevelInfo,
|
||||
Console: false,
|
||||
File: filepath.Join(dir, "server.log"),
|
||||
AuditFile: filepath.Join(dir, "audit.log"),
|
||||
})
|
||||
t.Cleanup(func() { _ = lg.Close() })
|
||||
|
||||
acl := NewDeviceACL(filepath.Join(dir, "device_acl.json"))
|
||||
if err := acl.Bind([]string{"1001"}, "alice@corp.com", "admin"); err != nil {
|
||||
t.Fatalf("bind 1001: %v", err)
|
||||
}
|
||||
if err := acl.Bind([]string{"1002"}, "bob@corp.com", "admin"); err != nil {
|
||||
t.Fatalf("bind 1002: %v", err)
|
||||
}
|
||||
wh := newWSHub(wsauth.New(), hub.New(), nil, lg).withDeviceACL(acl)
|
||||
t.Cleanup(wh.stop)
|
||||
|
||||
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1001"})
|
||||
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1002"})
|
||||
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1003"}) // public
|
||||
wh.log.Audit("mcp.tool.call", map[string]any{"device": "1001"})
|
||||
wh.log.Audit("admin.device.bind", map[string]any{"devices": []string{"1001"}, "owner": "alice@corp.com"})
|
||||
|
||||
query := func(user string) string {
|
||||
t.Helper()
|
||||
c, tok := aclTestClient(t, wh, user, "admin")
|
||||
raw, _ := json.Marshal(map[string]any{"token": tok, "limit": 50})
|
||||
wh.handleQueryAudit(c, raw)
|
||||
msg := readUntilCmd(t, c, "audit_result")
|
||||
if msg["ok"] != true {
|
||||
t.Fatalf("%s: reply = %+v", user, msg)
|
||||
}
|
||||
events, _ := json.Marshal(msg["events"])
|
||||
return string(events)
|
||||
}
|
||||
|
||||
alice := query("alice@corp.com")
|
||||
for _, want := range []string{`"device_id":"1001"`, `"device_id":"1003"`, `"device":"1001"`, `"devices":["1001"]`} {
|
||||
if !strings.Contains(alice, want) {
|
||||
t.Fatalf("alice events missing %s: %s", want, alice)
|
||||
}
|
||||
}
|
||||
if strings.Contains(alice, `"device_id":"1002"`) {
|
||||
t.Fatalf("alice saw bob's bound device: %s", alice)
|
||||
}
|
||||
|
||||
bob := query("bob@corp.com")
|
||||
if !strings.Contains(bob, `"device_id":"1002"`) {
|
||||
t.Fatalf("bob events missing his own device: %s", bob)
|
||||
}
|
||||
for _, leak := range []string{`"device_id":"1001"`, `"device":"1001"`, `"devices":["1001"]`} {
|
||||
if strings.Contains(bob, leak) {
|
||||
t.Fatalf("bob saw alice's bound device record %s: %s", leak, bob)
|
||||
}
|
||||
}
|
||||
|
||||
super := query("admin")
|
||||
for _, want := range []string{`"device_id":"1001"`, `"device_id":"1002"`, `"device":"1001"`, `"devices":["1001"]`} {
|
||||
if !strings.Contains(super, want) {
|
||||
t.Fatalf("superadmin events missing %s: %s", want, super)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryAuditHandlerDisabledFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
wh, _ := newAuditTestHubWithoutAuditFile(t, dir)
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeviceACLPersistAndReload(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_acl.json")
|
||||
a := NewDeviceACL(path)
|
||||
if err := a.Bind([]string{"dev1", "dev2"}, "a@corp.com", "admin"); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
if got := a.Owner("dev1"); got != "a@corp.com" {
|
||||
t.Fatalf("Owner(dev1) = %q", got)
|
||||
}
|
||||
|
||||
reloaded := NewDeviceACL(path)
|
||||
if err := reloaded.Load(); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if got := reloaded.Owner("dev2"); got != "a@corp.com" {
|
||||
t.Fatalf("reloaded Owner(dev2) = %q", got)
|
||||
}
|
||||
if got := reloaded.Owner("dev3"); got != "" {
|
||||
t.Fatalf("reloaded Owner(dev3) = %q, want empty", got)
|
||||
}
|
||||
|
||||
if err := reloaded.Unbind([]string{"dev1"}); err != nil {
|
||||
t.Fatalf("Unbind: %v", err)
|
||||
}
|
||||
again := NewDeviceACL(path)
|
||||
if err := again.Load(); err != nil {
|
||||
t.Fatalf("Load after unbind: %v", err)
|
||||
}
|
||||
if got := again.Owner("dev1"); got != "" {
|
||||
t.Fatalf("Owner(dev1) after unbind = %q", got)
|
||||
}
|
||||
if got := again.Owner("dev2"); got != "a@corp.com" {
|
||||
t.Fatalf("Owner(dev2) after unbind = %q", got)
|
||||
}
|
||||
|
||||
if err := again.Remove("dev2"); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
final := NewDeviceACL(path)
|
||||
if err := final.Load(); err != nil {
|
||||
t.Fatalf("Load after remove: %v", err)
|
||||
}
|
||||
if got := final.Snapshot(); len(got) != 0 {
|
||||
t.Fatalf("snapshot = %+v, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeviceACLMalformedFileIsAnError(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_acl.json")
|
||||
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
if err := NewDeviceACL(path).Load(); err == nil {
|
||||
t.Fatal("Load accepted a malformed file; private devices would become public")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeviceAllowedMatrix(t *testing.T) {
|
||||
acl := NewDeviceACL("")
|
||||
if err := acl.Bind([]string{"a-dev"}, "a@corp.com", "admin"); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
if err := acl.Bind([]string{"b-dev"}, "b@corp.com", "admin"); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
acl *DeviceACL
|
||||
username string
|
||||
role string
|
||||
device string
|
||||
want bool
|
||||
}{
|
||||
{"nil acl legacy allows all", nil, "any", "viewer", "pub", true},
|
||||
{"superadmin sees public", acl, "admin", "admin", "pub", true},
|
||||
{"superadmin sees bound", acl, "admin", "admin", "a-dev", true},
|
||||
{"admin sees public", acl, "c@corp.com", "admin", "pub", true},
|
||||
{"admin blocked on other's device", acl, "c@corp.com", "admin", "a-dev", false},
|
||||
{"owner sees own device", acl, "a@corp.com", "admin", "a-dev", true},
|
||||
{"owner blocked on other's device", acl, "a@corp.com", "admin", "b-dev", false},
|
||||
{"viewer sees no public device", acl, "v@corp.com", "viewer", "pub", false},
|
||||
{"viewer sees own device", acl, "a@corp.com", "viewer", "a-dev", true},
|
||||
{"empty username blocked", acl, "", "viewer", "a-dev", false},
|
||||
{"empty device blocked", acl, "admin", "admin", "", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := deviceAllowed(tt.acl, tt.username, tt.role, tt.device); got != tt.want {
|
||||
t.Fatalf("deviceAllowed(%q,%q,%q) = %v, want %v",
|
||||
tt.username, tt.role, tt.device, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+22
-5
@@ -32,6 +32,7 @@ type Server struct {
|
||||
hub *hub.Hub
|
||||
auth *wsauth.Authenticator
|
||||
history *devicehistory.Store // nil → no offline devices
|
||||
deviceACL *DeviceACL // nil → no per-device owner filtering
|
||||
ws *wsHub
|
||||
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
||||
loginIPLimit *wsauth.RateLimiter
|
||||
@@ -88,6 +89,10 @@ type Config struct {
|
||||
// session (cookie/header) into a YAMA web session via /sso. nil disables
|
||||
// SSO and the front-end falls back to the built-in login form.
|
||||
SSO SSODetector
|
||||
// DeviceACL is the per-device owner table. nil disables filtering (legacy
|
||||
// behaviour: every authenticated session sees every device). The shipped
|
||||
// server always wires one; tests may omit it.
|
||||
DeviceACL *DeviceACL
|
||||
}
|
||||
|
||||
// New creates an HTTP server bound to the given port. port=0 disables the server.
|
||||
@@ -115,6 +120,7 @@ func (s *Server) WithConfig(cfg Config) *Server {
|
||||
s.basePath = cfg.BasePath
|
||||
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
|
||||
s.sso = cfg.SSO
|
||||
s.deviceACL = cfg.DeviceACL
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -138,7 +144,8 @@ func (s *Server) Start() error {
|
||||
s.ws = newWSHub(s.auth, s.hub, s.history, s.log).
|
||||
withOriginAllowlist(s.allowedOrigins).
|
||||
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
||||
withTrustForwardedFor(s.trustForwardedFor)
|
||||
withTrustForwardedFor(s.trustForwardedFor).
|
||||
withDeviceACL(s.deviceACL)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", s.handleIndex)
|
||||
@@ -280,8 +287,17 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
// handleDevices returns a JSON snapshot of currently-online devices. Empty
|
||||
// array (not null) when no clients are connected — matches what the front-end
|
||||
// will eventually expect. Auth-gated via requireBearer.
|
||||
func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request, sess *wsauth.Session) {
|
||||
devices := s.hub.ListDevices()
|
||||
if s.deviceACL != nil {
|
||||
visible := make([]hub.DeviceInfo, 0, len(devices))
|
||||
for _, d := range devices {
|
||||
if deviceAllowed(s.deviceACL, sess.Username, sess.Role, d.ID) {
|
||||
visible = append(visible, d)
|
||||
}
|
||||
}
|
||||
devices = visible
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if err := json.NewEncoder(w).Encode(devices); err != nil {
|
||||
@@ -294,7 +310,7 @@ func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
|
||||
// missing / invalid / expired tokens. Used to gate REST endpoints that
|
||||
// previously fell through with no auth (notably /api/devices, which
|
||||
// otherwise leaks the full online-device list to anyone on the internet).
|
||||
func (s *Server) requireBearer(next http.HandlerFunc) http.HandlerFunc {
|
||||
func (s *Server) requireBearer(next func(http.ResponseWriter, *http.Request, *wsauth.Session)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
const prefix = "Bearer "
|
||||
hdr := r.Header.Get("Authorization")
|
||||
@@ -307,11 +323,12 @@ func (s *Server) requireBearer(next http.HandlerFunc) http.HandlerFunc {
|
||||
s.unauthorized(w)
|
||||
return
|
||||
}
|
||||
if _, err := s.auth.ValidateToken(token); err != nil {
|
||||
sess, err := s.auth.ValidateToken(token)
|
||||
if err != nil {
|
||||
s.unauthorized(w)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
next(w, r, sess)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,19 @@ func (s *Server) handleSSO(w http.ResponseWriter, r *http.Request) {
|
||||
s.unauthorized(w)
|
||||
return
|
||||
}
|
||||
// "admin" is the built-in superadmin account and must never be minted by
|
||||
// SSO: any portal identity with that name would inherit bind/unbind and
|
||||
// unrestricted device access. Portal usernames are email addresses, so a
|
||||
// real portal user can never legitimately hit this.
|
||||
if username == "admin" {
|
||||
fields := requestFields(r, s.trustForwardedFor)
|
||||
fields["method"] = "sso"
|
||||
fields["actor"] = username
|
||||
fields["reason"] = "reserved_username"
|
||||
s.log.AuditWarn(auditLoginFail, fields)
|
||||
s.unauthorized(w)
|
||||
return
|
||||
}
|
||||
// Only the "admin" role may skip the login form via SSO. Every other role
|
||||
// (viewer, unknown) must authenticate against YAMA's own login, even with
|
||||
// a valid portal session. A valid portal identity being refused here is
|
||||
|
||||
@@ -161,6 +161,7 @@ func TestHandleSSOAdminOnly(t *testing.T) {
|
||||
wantStatus int
|
||||
}{
|
||||
{"admin is bridged", &fakeSSODetector{"alice", "admin", true}, http.StatusOK},
|
||||
{"built-in username is rejected", &fakeSSODetector{"admin", "admin", true}, http.StatusUnauthorized},
|
||||
{"viewer is rejected", &fakeSSODetector{"bob", "viewer", true}, http.StatusUnauthorized},
|
||||
{"unknown role is rejected", &fakeSSODetector{"carol", "operator", true}, http.StatusUnauthorized},
|
||||
{"no credential is rejected", &fakeSSODetector{ok: false}, http.StatusUnauthorized},
|
||||
|
||||
+43
-3
@@ -131,7 +131,15 @@ func (c *wsClient) close() {
|
||||
// challengeCaps advertises optional protocol features. It is appended to every
|
||||
// challenge, including the rotation after a failed login, because the browser
|
||||
// overwrites its capability state on each challenge. Old frontends ignore it.
|
||||
const challengeCaps = `,"caps":{"multiWatch":true,"keyframeRequest":true,"offlineDevices":true,"auditLog":true}`
|
||||
// deviceAcl is only advertised when the hub actually has a binding table;
|
||||
// embedders that leave it nil keep the old "everyone sees everything" model.
|
||||
func (h *wsHub) challengeCaps() string {
|
||||
deviceAcl := "false"
|
||||
if h.acl != nil {
|
||||
deviceAcl = "true"
|
||||
}
|
||||
return `,"caps":{"multiWatch":true,"keyframeRequest":true,"offlineDevices":true,"auditLog":true,"deviceAcl":` + deviceAcl + `}`
|
||||
}
|
||||
|
||||
// maxWatchPerClient bounds the number of devices one WebSocket may stream at
|
||||
// once. The wall tops out at 25 tiles; the slack covers a focus switch racing
|
||||
@@ -152,6 +160,7 @@ type wsHub struct {
|
||||
auth *wsauth.Authenticator
|
||||
devices *hub.Hub
|
||||
history *devicehistory.Store // nil → device_list stays online-only
|
||||
acl *DeviceACL // nil → every device is public (tests/embedders)
|
||||
log *logger.Logger
|
||||
|
||||
mu sync.RWMutex
|
||||
@@ -210,6 +219,34 @@ func (h *wsHub) withTrustForwardedFor(trust bool) *wsHub {
|
||||
return h
|
||||
}
|
||||
|
||||
// withDeviceACL wires the per-device owner table. nil keeps the legacy
|
||||
// "every authenticated session may access every device" behaviour, which is
|
||||
// what embedders/tests without the ACL set up get.
|
||||
func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
|
||||
h.acl = acl
|
||||
return h
|
||||
}
|
||||
|
||||
// isSuperAdmin reports whether this session is the built-in admin account
|
||||
// (username "admin" + role admin). Other admin-role users — local accounts
|
||||
// created in the user panel or portal admins bridged by SSO — are device-
|
||||
// scoped by the ACL and must NOT be treated as superadmins.
|
||||
//
|
||||
// The "admin" username cannot be minted elsewhere: wsauth.CreateUser rejects
|
||||
// it, the users.json loader skips it, local password login rejects '@' names,
|
||||
// and handleSSO refuses a portal identity named "admin".
|
||||
func (c *wsClient) isSuperAdmin() bool {
|
||||
return c != nil && c.role == "admin" && c.user == "admin"
|
||||
}
|
||||
|
||||
// canAccessDevice applies the visibility matrix from deviceAllowed.
|
||||
func (h *wsHub) canAccessDevice(c *wsClient, deviceID string) bool {
|
||||
if c == nil || deviceID == "" {
|
||||
return false
|
||||
}
|
||||
return deviceAllowed(h.acl, c.user, c.role, deviceID)
|
||||
}
|
||||
|
||||
// checkOrigin decides whether to accept a WebSocket upgrade based on
|
||||
// the request's Origin header. Same-origin (Origin host == Host) is
|
||||
// always accepted; explicit allowlist entries cover the
|
||||
@@ -512,7 +549,10 @@ func (h *wsHub) OnDeviceUpdate(id string, rtt int, activeWindow string) {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for c := range h.clients {
|
||||
if c.token != "" {
|
||||
// Heartbeat data includes the device's foreground-window text. Sending
|
||||
// it to clients that cannot access the device would leak both its
|
||||
// existence and what its user is doing.
|
||||
if c.token != "" && deviceAllowed(h.acl, c.user, c.role, id) {
|
||||
c.queue(payload)
|
||||
}
|
||||
}
|
||||
@@ -673,7 +713,7 @@ func (h *wsHub) serve(w http.ResponseWriter, r *http.Request) {
|
||||
go h.writeLoop(client)
|
||||
|
||||
// Greet with a challenge nonce so the browser can compute the login response.
|
||||
client.queue([]byte(`{"cmd":"challenge","nonce":"` + nonce + `"` + challengeCaps + `}`))
|
||||
client.queue([]byte(`{"cmd":"challenge","nonce":"` + nonce + `"` + h.challengeCaps() + `}`))
|
||||
|
||||
h.readLoop(client)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
+398
-11
@@ -28,7 +28,7 @@ func (h *wsHub) rotateChallenge(c *wsClient) {
|
||||
}
|
||||
c.nonce = n
|
||||
// Must carry caps too: the browser replaces serverCaps on every challenge.
|
||||
c.queue([]byte(`{"cmd":"challenge","nonce":"` + n + `"` + challengeCaps + `}`))
|
||||
c.queue([]byte(`{"cmd":"challenge","nonce":"` + n + `"` + h.challengeCaps() + `}`))
|
||||
}
|
||||
|
||||
// dispatch routes one inbound message to its handler. The `raw` payload is
|
||||
@@ -96,6 +96,10 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
|
||||
h.handleDeleteUser(c, raw)
|
||||
case "list_users":
|
||||
h.handleListUsers(c, raw)
|
||||
case "bind_device":
|
||||
h.handleBindDevice(c, raw)
|
||||
case "unbind_device":
|
||||
h.handleUnbindDevice(c, raw)
|
||||
case "get_groups":
|
||||
h.handleGetGroups(c, raw)
|
||||
case "query_audit":
|
||||
@@ -136,6 +140,46 @@ func (h *wsHub) requireAdmin(c *wsClient, raw []byte, replyCmd string) (ok bool)
|
||||
return true
|
||||
}
|
||||
|
||||
// requireSuperAdmin is requireAdmin narrowed to the built-in "admin" account
|
||||
// (username "admin" + role admin). Other admin-role users — local accounts or
|
||||
// SSO portal admins — must not be able to bind devices.
|
||||
func (h *wsHub) requireSuperAdmin(c *wsClient, raw []byte, replyCmd string) (ok bool) {
|
||||
if !h.requireAuth(c, raw, replyCmd) {
|
||||
return false
|
||||
}
|
||||
if !c.isSuperAdmin() {
|
||||
c.statAdminDenied++
|
||||
h.audit(c, true, auditDenied, map[string]any{
|
||||
"operation": strings.TrimSuffix(replyCmd, "_result"),
|
||||
"reason": "not_superadmin",
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": false, "msg": "Superadmin only",
|
||||
}))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// denyIfNoDeviceAccess audits and (optionally) replies when c may not touch
|
||||
// deviceID. Returns true when the caller should stop processing.
|
||||
func (h *wsHub) denyIfNoDeviceAccess(c *wsClient, deviceID, replyCmd string) bool {
|
||||
if h.canAccessDevice(c, deviceID) {
|
||||
return false
|
||||
}
|
||||
if replyCmd != "" {
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": false, "id": deviceID, "msg": "Permission denied",
|
||||
}))
|
||||
}
|
||||
h.audit(c, true, auditDenied, map[string]any{
|
||||
"operation": strings.TrimSuffix(replyCmd, "_result"),
|
||||
"device_id": deviceID,
|
||||
"reason": "device_acl",
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// ----- handlers ------------------------------------------------------------
|
||||
|
||||
func (h *wsHub) handleGetSalt(c *wsClient, raw []byte) {
|
||||
@@ -214,6 +258,20 @@ func (h *wsHub) handleLogin(c *wsClient, raw []byte) {
|
||||
return
|
||||
}
|
||||
|
||||
// '@' is reserved for SSO identities. A local account with an email-shaped
|
||||
// username could otherwise log in with a password and inherit that SSO
|
||||
// user's device bindings; SSO itself authenticates through /sso.
|
||||
if strings.Contains(in.Username, "@") {
|
||||
c.statLoginFailures++
|
||||
h.audit(c, true, auditLoginFail, map[string]any{
|
||||
"username": in.Username,
|
||||
"reason": "sso_username_on_local_login",
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{"cmd": "login_result", "ok": false, "msg": "Invalid credentials"}))
|
||||
h.rotateChallenge(c)
|
||||
return
|
||||
}
|
||||
|
||||
// Bind the response to the challenge we issued at connect time so that
|
||||
// replays from a different connection can't reuse a captured response.
|
||||
if in.Nonce == "" || in.Nonce != c.nonce {
|
||||
@@ -267,10 +325,11 @@ func (h *wsHub) handleLogin(c *wsClient, raw []byte) {
|
||||
h.audit(c, false, auditLoginOK, fields)
|
||||
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": "login_result",
|
||||
"ok": true,
|
||||
"token": token,
|
||||
"role": role,
|
||||
"cmd": "login_result",
|
||||
"ok": true,
|
||||
"token": token,
|
||||
"role": role,
|
||||
"username": in.Username,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -471,6 +530,9 @@ func (h *wsHub) handleConnect(c *wsClient, raw []byte) {
|
||||
}
|
||||
return m
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, in.ID, "connect_result") {
|
||||
return
|
||||
}
|
||||
|
||||
var stopped []string
|
||||
starts := make(map[string]time.Time)
|
||||
@@ -637,6 +699,9 @@ func (h *wsHub) handleKeyframe(c *wsClient, raw []byte) {
|
||||
c.queue(mustJSON(reply(false, "Bad request")))
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, in.ID, "keyframe_result") {
|
||||
return
|
||||
}
|
||||
|
||||
allowed := false
|
||||
h.mu.Lock()
|
||||
@@ -693,6 +758,9 @@ func (h *wsHub) handleRdpReset(c *wsClient, raw []byte) {
|
||||
})
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, deviceID, "rdp_reset_result") {
|
||||
return
|
||||
}
|
||||
// CMD_RESTORE_CONSOLE must go through the screen sub-conn — the client
|
||||
// dispatches it from CScreenManager::OnReceive, which only reads from
|
||||
// the screen sub-conn (see client/ScreenManager.cpp:996). Sending on the
|
||||
@@ -717,12 +785,41 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
||||
return
|
||||
}
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": "device_list",
|
||||
"ok": true,
|
||||
"devices": h.listDevicesWithOffline(),
|
||||
"cmd": "device_list",
|
||||
"ok": true,
|
||||
"devices": h.listVisibleDevices(c),
|
||||
"username": c.user,
|
||||
"role": c.role,
|
||||
}))
|
||||
}
|
||||
|
||||
// deviceListItem is a DeviceInfo plus the owner field the superadmin UI needs.
|
||||
// Embedding keeps every DeviceInfo JSON field at the top level, so the
|
||||
// existing frontend keeps working unchanged.
|
||||
type deviceListItem struct {
|
||||
hub.DeviceInfo
|
||||
Owner string `json:"owner,omitempty"`
|
||||
}
|
||||
|
||||
// listVisibleDevices applies the device ACL to the online + offline snapshot.
|
||||
// Owner is only exposed to the superadmin; for everyone else a visible device
|
||||
// is either public or owned by the caller, so the field adds nothing.
|
||||
func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||
all := h.listDevicesWithOffline()
|
||||
out := make([]deviceListItem, 0, len(all))
|
||||
for _, d := range all {
|
||||
if !h.canAccessDevice(c, d.ID) {
|
||||
continue
|
||||
}
|
||||
owner := ""
|
||||
if h.acl != nil && c.isSuperAdmin() {
|
||||
owner = h.acl.Owner(d.ID)
|
||||
}
|
||||
out = append(out, deviceListItem{DeviceInfo: d, Owner: owner})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// listDevicesWithOffline returns the online snapshot followed by historical
|
||||
// devices that are not currently online. The online-ID set is derived from the
|
||||
// same snapshot, so a device reconnecting between the two lookups cannot appear
|
||||
@@ -818,6 +915,9 @@ func (h *wsHub) handleMouse(c *wsClient, raw []byte) {
|
||||
if deviceID == "" {
|
||||
return // browser hasn't picked a device yet
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, deviceID, "") {
|
||||
return
|
||||
}
|
||||
|
||||
var message, wParam uint64
|
||||
switch in.Type {
|
||||
@@ -940,6 +1040,9 @@ func (h *wsHub) handleKey(c *wsClient, raw []byte) {
|
||||
if deviceID == "" {
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, deviceID, "") {
|
||||
return
|
||||
}
|
||||
|
||||
var message uint64
|
||||
switch {
|
||||
@@ -1002,6 +1105,9 @@ func (h *wsHub) handleClipboardSet(c *wsClient, raw []byte) {
|
||||
})
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, deviceID, "clipboard_set_result") {
|
||||
return
|
||||
}
|
||||
gbk, err := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(in.Text))
|
||||
if err != nil {
|
||||
h.audit(c, true, auditClipSet, map[string]any{
|
||||
@@ -1046,6 +1152,9 @@ func (h *wsHub) handleClipboardGet(c *wsClient, raw []byte) {
|
||||
})
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, deviceID, "clipboard_get_result") {
|
||||
return
|
||||
}
|
||||
if err := h.devices.SendToScreen(deviceID, []byte{protocol.CommandScreenGetClipboard}); err != nil {
|
||||
h.audit(c, true, auditClipGet, map[string]any{
|
||||
"device_id": deviceID,
|
||||
@@ -1118,6 +1227,9 @@ func (h *wsHub) handleCreateUser(c *wsClient, raw []byte) {
|
||||
// Admin-only: this is destructive and irreversible.
|
||||
func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
const replyCmd = "delete_device_result"
|
||||
// Admin-role users intentionally keep the existing delete permission, even
|
||||
// for a device bound to someone else (product decision). The ACL row is
|
||||
// removed together with the device record below.
|
||||
if !h.requireAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
@@ -1145,6 +1257,9 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
if h.history != nil {
|
||||
h.history.Remove(in.ID)
|
||||
}
|
||||
// The device is gone; its binding must not survive a later
|
||||
// client that happens to reuse the same ID.
|
||||
h.dropDeviceBinding(in.ID)
|
||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||
"device_id": in.ID,
|
||||
"mode": "uninstall",
|
||||
@@ -1185,6 +1300,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
}))
|
||||
return
|
||||
}
|
||||
h.dropDeviceBinding(in.ID)
|
||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||
"device_id": in.ID,
|
||||
"mode": "removed",
|
||||
@@ -1216,7 +1332,56 @@ func (h *wsHub) handleDeleteUser(c *wsClient, raw []byte) {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Invalid JSON"}))
|
||||
return
|
||||
}
|
||||
// Deleting an account that owns bound devices releases those bindings.
|
||||
// Only the superadmin may do that: for any other admin-role user it would
|
||||
// both destroy another user and drop their devices into the public pool.
|
||||
var boundIDs []string
|
||||
if h.acl != nil {
|
||||
for id, e := range h.acl.Snapshot() {
|
||||
if e.Owner == in.Username {
|
||||
boundIDs = append(boundIDs, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(boundIDs) > 0 && !c.isSuperAdmin() {
|
||||
h.audit(c, true, auditUserDelete, map[string]any{
|
||||
"target": in.Username,
|
||||
"ok": false,
|
||||
"reason": "not_superadmin",
|
||||
"devices": len(boundIDs),
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": false,
|
||||
"msg": "Only the superadmin can delete an account with bound devices",
|
||||
}))
|
||||
return
|
||||
}
|
||||
// Release the bindings before deleting the account, and abort on a
|
||||
// persistence error (Unbind is atomic): leaving them behind would keep the
|
||||
// devices hidden from every non-superadmin. If the account deletion then
|
||||
// fails, bind them back so the account never loses control of its devices.
|
||||
if len(boundIDs) > 0 {
|
||||
if err := h.acl.Unbind(boundIDs); err != nil {
|
||||
h.audit(c, true, auditUserDelete, map[string]any{
|
||||
"target": in.Username,
|
||||
"ok": false,
|
||||
"reason": "unbind_failed",
|
||||
"error": err.Error(),
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": false,
|
||||
"msg": "Failed to release device bindings: " + err.Error(),
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
unbound := 0
|
||||
if err := h.auth.DeleteUser(in.Username); err != nil {
|
||||
if len(boundIDs) > 0 {
|
||||
if rberr := h.acl.Bind(boundIDs, in.Username, c.user); rberr != nil {
|
||||
h.log.Warn("restore bindings of undeleted user %s: %v", in.Username, rberr)
|
||||
}
|
||||
}
|
||||
h.audit(c, true, auditUserDelete, map[string]any{
|
||||
"target": in.Username,
|
||||
"ok": false,
|
||||
@@ -1226,11 +1391,19 @@ func (h *wsHub) handleDeleteUser(c *wsClient, raw []byte) {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": err.Error()}))
|
||||
return
|
||||
}
|
||||
if len(boundIDs) > 0 {
|
||||
unbound = len(boundIDs)
|
||||
h.revalidateDeviceSessions(boundIDs)
|
||||
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
|
||||
}
|
||||
h.audit(c, false, auditUserDelete, map[string]any{
|
||||
"target": in.Username,
|
||||
"ok": true,
|
||||
"target": in.Username,
|
||||
"ok": true,
|
||||
"unbound_devices": unbound,
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": true}))
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": true, "unbound_devices": unbound,
|
||||
}))
|
||||
}
|
||||
|
||||
// handleListUsers returns the account table to admin callers. Field shape
|
||||
@@ -1273,6 +1446,11 @@ func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) {
|
||||
}
|
||||
seen := map[string]struct{}{"default": {}}
|
||||
for _, d := range h.devices.ListDevices() {
|
||||
// Group names are device metadata: do not reveal groups that only
|
||||
// exist on devices this caller may not see.
|
||||
if !h.canAccessDevice(c, d.ID) {
|
||||
continue
|
||||
}
|
||||
g := d.Group
|
||||
if g == "" {
|
||||
g = "default"
|
||||
@@ -1291,6 +1469,212 @@ func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) {
|
||||
}))
|
||||
}
|
||||
|
||||
// handleBindDevice assigns one or more devices to a username. Superadmin only.
|
||||
//
|
||||
// username may be a local account (must already exist) or an SSO identity
|
||||
// (email form; no local record is required because the server never sees the
|
||||
// portal's user list). Binding to "admin" is rejected: the built-in
|
||||
// superadmin already sees everything and owns no device rows.
|
||||
func (h *wsHub) handleBindDevice(c *wsClient, raw []byte) {
|
||||
const replyCmd = "bind_device_result"
|
||||
if !h.requireSuperAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
IDs []string `json:"ids"`
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
ids := normalizeDeviceIDs(in.IDs, in.ID)
|
||||
username := strings.TrimSpace(in.Username)
|
||||
|
||||
fail := func(msg string) {
|
||||
h.audit(c, true, auditDeviceBind, map[string]any{
|
||||
"ok": false,
|
||||
"reason": "invalid_request",
|
||||
"error": msg,
|
||||
"owner": username,
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": msg}))
|
||||
}
|
||||
switch {
|
||||
case len(ids) == 0:
|
||||
fail("No device ids")
|
||||
return
|
||||
case username == "":
|
||||
fail("Username is required")
|
||||
return
|
||||
case len(username) > 128:
|
||||
fail("Username is too long")
|
||||
return
|
||||
case username == "admin":
|
||||
fail("Cannot bind devices to the built-in admin account")
|
||||
return
|
||||
case h.acl == nil:
|
||||
fail("Device ACL is not enabled on this server")
|
||||
return
|
||||
}
|
||||
if !strings.Contains(username, "@") {
|
||||
if _, exists := h.auth.GetSalt(username); !exists {
|
||||
fail("Unknown local user; SSO users must be email addresses")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := h.acl.Bind(ids, username, c.user); err != nil {
|
||||
fail("Failed to save binding: " + err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Anyone who no longer passes the ACL loses their live session.
|
||||
h.revalidateDeviceSessions(ids)
|
||||
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
|
||||
h.audit(c, false, auditDeviceBind, map[string]any{
|
||||
"devices": ids,
|
||||
"owner": username,
|
||||
"ok": true,
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": true, "count": len(ids)}))
|
||||
}
|
||||
|
||||
// handleUnbindDevice returns devices to the public pool. Superadmin only.
|
||||
func (h *wsHub) handleUnbindDevice(c *wsClient, raw []byte) {
|
||||
const replyCmd = "unbind_device_result"
|
||||
if !h.requireSuperAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
IDs []string `json:"ids"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
ids := normalizeDeviceIDs(in.IDs, in.ID)
|
||||
if len(ids) == 0 {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "No device ids"}))
|
||||
return
|
||||
}
|
||||
if h.acl == nil {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Device ACL is not enabled on this server"}))
|
||||
return
|
||||
}
|
||||
if err := h.acl.Unbind(ids); err != nil {
|
||||
h.audit(c, true, auditDeviceUnbind, map[string]any{
|
||||
"devices": ids,
|
||||
"ok": false,
|
||||
"error": err.Error(),
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Failed to save binding: " + err.Error()}))
|
||||
return
|
||||
}
|
||||
// A former owner with viewer role loses access when the device returns to
|
||||
// the public (admin-only) pool; admin-role users keep watching it.
|
||||
h.revalidateDeviceSessions(ids)
|
||||
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
|
||||
h.audit(c, false, auditDeviceUnbind, map[string]any{
|
||||
"devices": ids,
|
||||
"ok": true,
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": true, "count": len(ids)}))
|
||||
}
|
||||
|
||||
// normalizeDeviceIDs merges the batch and single-device forms, trims blanks
|
||||
// and dedupes while preserving order.
|
||||
func normalizeDeviceIDs(ids []string, single string) []string {
|
||||
seen := make(map[string]struct{}, len(ids)+1)
|
||||
out := make([]string, 0, len(ids)+1)
|
||||
add := func(s string) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := seen[s]; ok {
|
||||
return
|
||||
}
|
||||
seen[s] = struct{}{}
|
||||
out = append(out, s)
|
||||
}
|
||||
for _, id := range ids {
|
||||
add(id)
|
||||
}
|
||||
add(single)
|
||||
return out
|
||||
}
|
||||
|
||||
// revalidateDeviceSessions drops screen/terminal sessions of clients that no
|
||||
// longer pass the ACL for the given devices. Called after any binding change:
|
||||
//
|
||||
// bind -> the old owner and every other non-owner lose access
|
||||
// unbind -> viewers lose access (the device becomes public: admin-only)
|
||||
//
|
||||
// Admin-role users and the superadmin keep sessions they are still entitled to.
|
||||
func (h *wsHub) revalidateDeviceSessions(ids []string) {
|
||||
type revoked struct {
|
||||
c *wsClient
|
||||
id string
|
||||
term bool
|
||||
}
|
||||
var events []revoked
|
||||
screenIDs := make(map[string]struct{})
|
||||
termIDs := make(map[string]struct{})
|
||||
|
||||
h.mu.Lock()
|
||||
for c := range h.clients {
|
||||
for _, id := range ids {
|
||||
if deviceAllowed(h.acl, c.user, c.role, id) {
|
||||
continue
|
||||
}
|
||||
if _, ok := c.watchIDs[id]; ok {
|
||||
delete(c.watchIDs, id)
|
||||
delete(c.keyframeAt, id)
|
||||
delete(c.watchStartedAt, id)
|
||||
screenIDs[id] = struct{}{}
|
||||
events = append(events, revoked{c: c, id: id})
|
||||
}
|
||||
if c.termWatching == id {
|
||||
c.termWatching = ""
|
||||
c.termStartedAt = time.Time{}
|
||||
termIDs[id] = struct{}{}
|
||||
events = append(events, revoked{c: c, id: id, term: true})
|
||||
}
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
for _, e := range events {
|
||||
msg := "Access to this device was revoked"
|
||||
if e.term {
|
||||
e.c.queue(mustJSON(map[string]any{
|
||||
"cmd": "term_closed", "ok": false, "id": e.id, "msg": msg,
|
||||
}))
|
||||
} else {
|
||||
e.c.queue(mustJSON(map[string]any{
|
||||
"cmd": "device_revoked", "id": e.id, "msg": msg,
|
||||
}))
|
||||
}
|
||||
}
|
||||
for id := range screenIDs {
|
||||
if h.countWatchers(id) == 0 {
|
||||
// Revocation is not a transient disconnect: stop capture now
|
||||
// instead of waiting out the reconnect grace period.
|
||||
h.devices.CloseScreen(id)
|
||||
}
|
||||
}
|
||||
for id := range termIDs {
|
||||
h.devices.CloseTerminalSession(id)
|
||||
}
|
||||
}
|
||||
|
||||
// dropDeviceBinding removes a deleted device's ACL entry so a future client
|
||||
// reusing the same ID cannot inherit the old owner.
|
||||
func (h *wsHub) dropDeviceBinding(deviceID string) {
|
||||
if h.acl == nil {
|
||||
return
|
||||
}
|
||||
if err := h.acl.Remove(deviceID); err != nil {
|
||||
h.log.Warn("device acl 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
|
||||
@@ -1312,6 +1696,9 @@ func (h *wsHub) handleTermOpen(c *wsClient, raw []byte) {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Bad request"}))
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, in.ID, replyCmd) {
|
||||
return
|
||||
}
|
||||
|
||||
// Pin termWatching BEFORE asking the hub to open the session: the
|
||||
// device's shell sub-conn can arrive in <100 ms on LAN, and
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -134,6 +135,12 @@ func (a *Authenticator) CreateUser(username, plainPassword, role string, allowed
|
||||
if username == "admin" {
|
||||
return errors.New("'admin' is reserved")
|
||||
}
|
||||
// '@' is reserved for SSO identities (portal usernames are email addresses).
|
||||
// Keeping the two namespaces disjoint means a local account can never be
|
||||
// created that would inherit an SSO user's device bindings.
|
||||
if strings.Contains(username, "@") {
|
||||
return errors.New("local usernames must not contain '@' (reserved for SSO)")
|
||||
}
|
||||
if role != "admin" && role != "viewer" {
|
||||
return errors.New("role must be 'admin' or 'viewer'")
|
||||
}
|
||||
@@ -342,6 +349,9 @@ func (a *Authenticator) SetUsersFile(path string) error {
|
||||
if e.Username == "" || e.Username == "admin" {
|
||||
continue
|
||||
}
|
||||
// Legacy records with '@' stay loaded (dropping them silently would
|
||||
// orphan their device bindings); the web login handler rejects local
|
||||
// logins with an SSO-shaped username instead.
|
||||
if e.PasswordHash == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package wsauth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -200,3 +203,43 @@ func TestRateLimiterNilSafe(t *testing.T) {
|
||||
r.Reset("anything")
|
||||
r.Sweep()
|
||||
}
|
||||
|
||||
// TestCreateUserRejectsAtSign keeps the local and SSO namespaces disjoint:
|
||||
// '@' is reserved for portal identities, so a locally-created account can
|
||||
// never inherit an SSO user's device bindings.
|
||||
func TestCreateUserRejectsAtSign(t *testing.T) {
|
||||
a := New()
|
||||
if err := a.CreateUser("user@corp.com", "pw", "admin", nil); err == nil {
|
||||
t.Fatal("CreateUser accepted an '@' username")
|
||||
}
|
||||
if err := a.CreateUser("alice", "pw", "admin", nil); err != nil {
|
||||
t.Fatalf("CreateUser(alice): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUsersFileLoadsLegacyAtSignRecord: the loader keeps legacy '@' records
|
||||
// (dropping them silently would orphan their device bindings). The web login
|
||||
// handler is what rejects password logins for SSO-shaped usernames.
|
||||
func TestUsersFileLoadsLegacyAtSignRecord(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "users.json")
|
||||
data, err := json.Marshal(usersFile{Users: []usersFileEntry{
|
||||
{Username: "legacy@corp.com", PasswordHash: "hash", Salt: "salt", Role: "admin"},
|
||||
{Username: "alice", PasswordHash: "hash", Salt: "salt", Role: "admin"},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
a := New()
|
||||
if err := a.SetUsersFile(path); err != nil {
|
||||
t.Fatalf("SetUsersFile: %v", err)
|
||||
}
|
||||
if _, ok := a.GetSalt("legacy@corp.com"); !ok {
|
||||
t.Fatal("loader dropped a legacy '@' record")
|
||||
}
|
||||
if _, ok := a.GetSalt("alice"); !ok {
|
||||
t.Fatal("loader dropped a valid local user")
|
||||
}
|
||||
}
|
||||
+187
-7
@@ -669,7 +669,8 @@
|
||||
.device-card .card-icon-btn:active { transform: scale(0.92); }
|
||||
.device-card .card-term-btn:hover { background: rgba(76, 175, 80, 0.25); color: #4caf50; }
|
||||
.device-card .card-del-btn:hover { background: rgba(231, 76, 60, 0.25); color: #e74c3c; }
|
||||
.device-card h3 { padding-right: 86px; } /* 给右上角两个操作图标让位 */
|
||||
.device-card .card-bind-btn:hover { background: rgba(230, 126, 34, 0.25); color: #e67e22; }
|
||||
.device-card h3 { padding-right: 124px; } /* 给右上角操作图标让位 */
|
||||
.device-grid.list-view .device-card .card-actions {
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
@@ -2173,6 +2174,34 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Device Binding Modal(仅内置 admin 超级管理员可见) -->
|
||||
<div class="modal-overlay" id="bind-device-modal" onclick="if(event.target===this)closeBindModal()">
|
||||
<div class="modal-content" style="max-width:440px;">
|
||||
<div class="modal-header">
|
||||
<h3>Device Binding</h3>
|
||||
<button class="modal-close" onclick="closeBindModal()">×</button>
|
||||
</div>
|
||||
<div class="user-form">
|
||||
<div id="bind-device-name" style="font-size:13px;color:#aaa;margin-bottom:10px;"></div>
|
||||
<label style="font-size:13px;color:#aaa;display:block;margin:8px 0 4px;">
|
||||
Owner (local username or SSO email)
|
||||
</label>
|
||||
<input type="text" id="bind-owner" list="bind-owner-options"
|
||||
placeholder="alice or user@corp.com" autocomplete="off">
|
||||
<datalist id="bind-owner-options"></datalist>
|
||||
<div style="font-size:12px;color:#888;margin-top:8px;">
|
||||
Bound devices are hidden from every other user except the built-in admin.
|
||||
Unbind returns the device to the public pool. SSO usernames are email
|
||||
addresses and must match the portal username exactly.
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;margin-top:14px;">
|
||||
<button onclick="confirmBindDevice()">Bind</button>
|
||||
<button class="cancel-btn" onclick="confirmUnbindDevice()">Unbind</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Generic alert / confirmation dialog. Replaces native alert()/confirm():
|
||||
their button labels come from the browser locale (e.g. German on a
|
||||
German system) and do not match the app. -->
|
||||
@@ -2387,7 +2416,7 @@
|
||||
};
|
||||
|
||||
// 服务端能力协商:旧 C++ / Go 服务端没有 caps,前端隐藏 Wall。
|
||||
let serverCaps = { multiWatch: false, keyframeRequest: false, offlineDevices: false, auditLog: false };
|
||||
let serverCaps = { multiWatch: false, keyframeRequest: false, offlineDevices: false, auditLog: false, deviceAcl: false };
|
||||
|
||||
// 离线设备开关:localStorage 只保存用户偏好,是否可用由服务端能力位决定。
|
||||
// 关闭时只影响 Grid/List;Wall 侧边栏始终列出离线设备(灰显、不可操作)。
|
||||
@@ -2734,8 +2763,10 @@
|
||||
if (!data || !data.token) return false;
|
||||
token = data.token;
|
||||
currentUserRole = data.role || 'viewer';
|
||||
currentUsername = data.username || '';
|
||||
localStorage.setItem('token', token);
|
||||
localStorage.setItem('role', currentUserRole);
|
||||
localStorage.setItem('username', currentUsername);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
@@ -2840,7 +2871,8 @@
|
||||
multiWatch: !!(msg.caps && msg.caps.multiWatch),
|
||||
keyframeRequest: !!(msg.caps && msg.caps.keyframeRequest),
|
||||
offlineDevices: !!(msg.caps && msg.caps.offlineDevices),
|
||||
auditLog: !!(msg.caps && msg.caps.auditLog)
|
||||
auditLog: !!(msg.caps && msg.caps.auditLog),
|
||||
deviceAcl: !!(msg.caps && msg.caps.deviceAcl)
|
||||
};
|
||||
updateWallAvailability();
|
||||
applyOfflineCapability();
|
||||
@@ -2859,8 +2891,10 @@
|
||||
if (msg.ok) {
|
||||
token = msg.token;
|
||||
currentUserRole = msg.role || 'viewer';
|
||||
currentUsername = msg.username || currentUsername;
|
||||
localStorage.setItem('token', token);
|
||||
localStorage.setItem('role', currentUserRole);
|
||||
localStorage.setItem('username', currentUsername);
|
||||
document.getElementById('login-error').textContent = '';
|
||||
// Show Users / Audit Log buttons for admin only
|
||||
updateAdminButtons();
|
||||
@@ -2879,11 +2913,22 @@
|
||||
token = null;
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('role');
|
||||
localStorage.removeItem('username');
|
||||
currentUserRole = 'viewer';
|
||||
currentUsername = '';
|
||||
updateAdminButtons();
|
||||
showPage('login-page');
|
||||
break;
|
||||
}
|
||||
if (msg.username && msg.username !== currentUsername) {
|
||||
currentUsername = msg.username;
|
||||
localStorage.setItem('username', currentUsername);
|
||||
}
|
||||
if (msg.role && msg.role !== currentUserRole) {
|
||||
currentUserRole = msg.role;
|
||||
localStorage.setItem('role', currentUserRole);
|
||||
}
|
||||
updateAdminButtons();
|
||||
devices = msg.devices || [];
|
||||
// Keep current page (renderDeviceList adjusts if out of range)
|
||||
renderDeviceList();
|
||||
@@ -3149,7 +3194,10 @@
|
||||
break;
|
||||
case 'delete_user_result':
|
||||
if (msg.ok) {
|
||||
showUserMsg('User deleted', false);
|
||||
const unbound = msg.unbound_devices || 0;
|
||||
showUserMsg(unbound > 0
|
||||
? 'User deleted; ' + unbound + ' device binding(s) released'
|
||||
: 'User deleted', false);
|
||||
listUsers();
|
||||
} else {
|
||||
showUserMsg(msg.msg || 'Failed to delete user', true);
|
||||
@@ -3166,9 +3214,44 @@
|
||||
break;
|
||||
case 'list_users_result':
|
||||
if (msg.ok) {
|
||||
// The built-in admin is the superadmin, never a bind target.
|
||||
knownLocalUsers = (msg.users || [])
|
||||
.map(u => u.username)
|
||||
.filter(u => u && u !== 'admin');
|
||||
renderUsersList(msg.users);
|
||||
const bindModal = document.getElementById('bind-device-modal');
|
||||
if (bindModal && bindModal.classList.contains('active')) {
|
||||
populateBindOwnerOptions();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'bind_device_result':
|
||||
if (msg.ok) {
|
||||
closeBindModal();
|
||||
getDevices();
|
||||
} else {
|
||||
appAlert(msg.msg || 'Failed to bind device', 'Device Binding');
|
||||
}
|
||||
break;
|
||||
case 'unbind_device_result':
|
||||
if (msg.ok) {
|
||||
closeBindModal();
|
||||
getDevices();
|
||||
} else {
|
||||
appAlert(msg.msg || 'Failed to unbind device', 'Device Binding');
|
||||
}
|
||||
break;
|
||||
case 'device_revoked': {
|
||||
// The superadmin bound this device to someone else while we
|
||||
// were watching it. Stop streaming immediately.
|
||||
const rid = String(msg.id);
|
||||
if (currentDevice && String(currentDevice.id) === rid) {
|
||||
appAlert(msg.msg || 'Access to this device was revoked', 'Access Revoked');
|
||||
disconnect();
|
||||
}
|
||||
getDevices();
|
||||
break;
|
||||
}
|
||||
case 'groups':
|
||||
if (msg.ok) {
|
||||
renderGroupsCheckboxes(msg.groups);
|
||||
@@ -4962,17 +5045,27 @@
|
||||
if (!offline) {
|
||||
actions.push(
|
||||
'<button class="card-icon-btn card-term-btn" title="Open Terminal" aria-label="Terminal" ' +
|
||||
'onclick="event.stopPropagation();openTerminal(\'' + d.id + '\')">' +
|
||||
'onclick="event.stopPropagation();openTerminal(\'' + jsAttr(d.id) + '\')">' +
|
||||
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>' +
|
||||
'</svg>' +
|
||||
'</button>');
|
||||
}
|
||||
if (canBindDevices()) {
|
||||
actions.push(
|
||||
'<button class="card-icon-btn card-bind-btn" title="Bind owner" aria-label="Bind owner" ' +
|
||||
'onclick="event.stopPropagation();openBindModal(\'' + jsAttr(d.id) + '\')">' +
|
||||
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<rect x="3" y="11" width="18" height="11" rx="2"/>' +
|
||||
'<path d="M7 11V7a5 5 0 0 1 10 0v4"/>' +
|
||||
'</svg>' +
|
||||
'</button>');
|
||||
}
|
||||
if (canDeleteDevices()) {
|
||||
actions.push(
|
||||
'<button class="card-icon-btn card-del-btn" title="' +
|
||||
(offline ? 'Delete record' : 'Uninstall host') + '" aria-label="Delete" ' +
|
||||
'onclick="event.stopPropagation();askDeleteDevice(\'' + d.id + '\')">' +
|
||||
'onclick="event.stopPropagation();askDeleteDevice(\'' + jsAttr(d.id) + '\')">' +
|
||||
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<polyline points="3 6 5 6 21 6"/>' +
|
||||
'<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>' +
|
||||
@@ -4984,7 +5077,7 @@
|
||||
const actionsHtml = actions.length
|
||||
? '<div class="card-actions">' + actions.join('') + '</div>' : '';
|
||||
return '<div class="device-card' + (offline ? ' offline' : '') + '"' +
|
||||
(offline ? '' : ' onclick="connectDevice(\'' + d.id + '\')"') + '>' +
|
||||
(offline ? '' : ' onclick="connectDevice(\'' + jsAttr(d.id) + '\')"') + '>' +
|
||||
actionsHtml +
|
||||
'<h3>' + escapeHtml(displayName(d)) + '</h3>' +
|
||||
'<div class="info-row">' +
|
||||
@@ -4992,6 +5085,9 @@
|
||||
'<div class="info"><span class="info-label">Loc:</span> ' + escapeHtml(loc) + '</div>' +
|
||||
'</div>' +
|
||||
'<div class="info"><span class="info-label">OS:</span> ' + escapeHtml(d.os || '-') + '</div>' +
|
||||
(isSuperAdmin() && d.owner
|
||||
? '<div class="info"><span class="info-label">Owner:</span> ' + escapeHtml(d.owner) + '</div>'
|
||||
: '') +
|
||||
'<div class="meta-row">' +
|
||||
(offline
|
||||
? '<span class="meta-item offline-badge">Offline</span>'
|
||||
@@ -5141,8 +5237,10 @@
|
||||
connectWebSocket(); // Reconnect immediately
|
||||
token = null;
|
||||
currentUserRole = 'viewer';
|
||||
currentUsername = '';
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('role');
|
||||
localStorage.removeItem('username');
|
||||
// 分组过滤器是按账号的临时偏好:换账号不应继承上一个账号的选择。
|
||||
selectedGroups = [];
|
||||
groupDropdownOpen = false;
|
||||
@@ -5224,6 +5322,69 @@
|
||||
});
|
||||
}
|
||||
|
||||
// ===== 设备绑定(仅内置 admin 超级管理员) =====
|
||||
// 绑定后该设备从其他 admin/viewer 的列表中消失,只有 owner 和内置 admin
|
||||
// 可见可控。服务端强制;前端只负责入口和展示。
|
||||
let pendingBindDeviceId = null;
|
||||
let knownLocalUsers = [];
|
||||
|
||||
function isSuperAdmin() {
|
||||
return currentUserRole === 'admin' && currentUsername === 'admin';
|
||||
}
|
||||
|
||||
function canBindDevices() {
|
||||
return !!(serverCaps.deviceAcl && isSuperAdmin());
|
||||
}
|
||||
|
||||
function populateBindOwnerOptions() {
|
||||
const dl = document.getElementById('bind-owner-options');
|
||||
if (!dl) return;
|
||||
dl.innerHTML = knownLocalUsers.map(u =>
|
||||
'<option value="' + escapeHtml(u) + '"></option>').join('');
|
||||
}
|
||||
|
||||
function openBindModal(id) {
|
||||
if (!canBindDevices()) return;
|
||||
const d = devices.find(x => String(x.id) === String(id));
|
||||
if (!d) { appAlert('Device not found.', 'Device Binding'); return; }
|
||||
pendingBindDeviceId = String(id);
|
||||
document.getElementById('bind-device-name').textContent =
|
||||
displayName(d) + ' (' + String(id) + ')';
|
||||
const ownerInput = document.getElementById('bind-owner');
|
||||
ownerInput.value = d.owner || '';
|
||||
populateBindOwnerOptions();
|
||||
document.getElementById('bind-device-modal').classList.add('active');
|
||||
// Refresh the local-user suggestions (list_users is admin-only, and
|
||||
// the superadmin is an admin). SSO emails are free-text.
|
||||
if (ws && ws.readyState === WebSocket.OPEN && token) {
|
||||
ws.send(JSON.stringify({ cmd: 'list_users', token }));
|
||||
}
|
||||
}
|
||||
|
||||
function closeBindModal() {
|
||||
pendingBindDeviceId = null;
|
||||
document.getElementById('bind-device-modal').classList.remove('active');
|
||||
}
|
||||
|
||||
function confirmBindDevice() {
|
||||
if (!pendingBindDeviceId || !ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
const username = document.getElementById('bind-owner').value.trim();
|
||||
if (!username) {
|
||||
appAlert('Enter a local username or an SSO email address.', 'Device Binding');
|
||||
return;
|
||||
}
|
||||
ws.send(JSON.stringify({
|
||||
cmd: 'bind_device', token, ids: [pendingBindDeviceId], username,
|
||||
}));
|
||||
}
|
||||
|
||||
function confirmUnbindDevice() {
|
||||
if (!pendingBindDeviceId || !ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
ws.send(JSON.stringify({
|
||||
cmd: 'unbind_device', token, ids: [pendingBindDeviceId],
|
||||
}));
|
||||
}
|
||||
|
||||
// ===== 删除设备 =====
|
||||
// 两种情况都删除服务端 devices.json 中的历史记录;在线设备额外按 MFC
|
||||
// 的做法发送单字节 TOKEN_UNINSTALL(卸载主机)。都先弹二次确认。
|
||||
@@ -5268,6 +5429,10 @@
|
||||
|
||||
// User Management Functions
|
||||
let currentUserRole = 'viewer';
|
||||
// Username of the current session. Only the built-in "admin" account is
|
||||
// the superadmin allowed to bind devices; other admin-role users keep
|
||||
// their existing UI but are subject to the device ACL server-side.
|
||||
let currentUsername = '';
|
||||
|
||||
function openUsersModal() {
|
||||
document.getElementById('users-modal').classList.add('active');
|
||||
@@ -7650,6 +7815,20 @@
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// Safely embed a value inside a single-quoted JS string that itself
|
||||
// sits in a double-quoted HTML attribute. Device IDs are client-
|
||||
// supplied, so never interpolate them raw into onclick handlers.
|
||||
function jsAttr(value) {
|
||||
const s = String(value == null ? '' : value)
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/</g, '\\x3c')
|
||||
.replace(/>/g, '\\x3e');
|
||||
return escapeHtml(s);
|
||||
}
|
||||
|
||||
// 设备显示名:有备注则 "hostname (备注)",否则就是 hostname。
|
||||
// 服务端备注从 m_ClientMap MAP_NOTE 取(参看 BuildDeviceListJson)。
|
||||
function displayName(d) {
|
||||
@@ -7925,6 +8104,7 @@
|
||||
// Restore token and role from localStorage (local-login fallback).
|
||||
token = localStorage.getItem('token');
|
||||
currentUserRole = localStorage.getItem('role') || 'viewer';
|
||||
currentUsername = localStorage.getItem('username') || '';
|
||||
// Attempt portal SSO first: if the user is already logged into the
|
||||
// parent domain, the server bridges the portal session cookie into
|
||||
// a YAMA session token so the login form is skipped. On failure
|
||||
|
||||
Reference in new issue
Block a user