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:
yuanyuanxiangandClaude Code committed 2026-11-19 11:17:51 +01:00
1 parent db148c4a69
commit 46434b46d0
16 files changed
+1716 -30

No files matched your search

+398 -11
View File
@@ -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