Files
SimpleRemoter/server/go/web/device_acl.go
T
yuanyuanxiangandClaude Code 46434b46d0 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>
2026-11-19 11:17:51 +01:00

253 lines
6.4 KiB
Go

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
}