Files
SimpleRemoter/server/go/auditquery/auditquery.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

334 lines
9.6 KiB
Go

// Package auditquery scans the server's JSON-lines audit file.
//
// The server writes its own audit records to logs/audit.log (see
// logger.AuditAt); records are already redacted at write time, so returning
// raw fields to an authenticated viewer is safe as long as we never widen what
// is written.
//
// Only the CURRENT audit file is searched. Rotated files (audit-*.log[.gz])
// are deliberately out of scope: they need gzip support and a separate index,
// and both the web UI and the MCP tool exist for recent-window triage ("what
// happened just now").
//
// The package is shared by web/audit_query.go (admin audit page) and the MCP
// get_audit_log tool, which is why it has no dependency on either.
package auditquery
import (
"bufio"
"encoding/json"
"os"
"strings"
"time"
)
const (
// DefaultLimit is used when the caller asks for no limit (0 or negative).
DefaultLimit = 100
// MaxLimit caps how many records one query may return.
MaxLimit = 1000
// MaxOffset caps how far a query may page into the result set.
MaxOffset = 10000
// scanBudget bounds how much of the audit file a single query reads. The
// tail is read when the file is larger, so the newest records (what
// operators actually triage) are always covered and a multi-GB log cannot
// stall the query goroutine.
scanBudget = 32 << 20 // 32 MB
)
// Query is one audit-log search. All filters are optional and combined with
// AND. Limit/Offset are clamped by Scan; callers that report the effective
// values back should clamp first with ClampLimit/ClampOffset.
type Query struct {
From string `json:"from"` // RFC3339 ("2026-10-18T10:00:00Z"), optional
To string `json:"to"` // RFC3339, optional
Event string `json:"event"` // exact ("web.login.failure"), prefix ("web." / "web.*"), or ""
Actor string `json:"actor"` // exact, case-insensitive
IP string `json:"ip"` // exact
DeviceID string `json:"device_id"`
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.
EventContains string `json:"event_contains"`
Limit int `json:"limit"`
Offset int `json:"offset"` // skip the newest N matching records
}
// Result is the outcome of scanning the audit file.
type Result struct {
Events []map[string]any // newest-first
Total int // matching records in the scanned window
TotalAll int // audit records in the scanned window before filters
FileExists bool
FileSize int64
ScannedBytes int64
Truncated bool // the file was larger than the scan budget
}
// ClampLimit bounds n to [1, max]. A non-positive n means DefaultLimit; a
// non-positive max means MaxLimit. Callers with a tighter UI cap (the web
// audit page uses 500) pass it as max.
func ClampLimit(n, max int) int {
if max <= 0 {
max = MaxLimit
}
if n <= 0 {
return DefaultLimit
}
if n > max {
return max
}
return n
}
// ClampOffset bounds n to [0, MaxOffset].
func ClampOffset(n int) int {
if n < 0 {
return 0
}
if n > MaxOffset {
return MaxOffset
}
return n
}
// Scan scans path for audit records matching q. The returned events are the
// newest Limit records after skipping Offset, in newest-first order. A missing
// file is not an error: no audit record has been written yet (the logger
// creates the file lazily), so the result is empty with FileExists=false.
func Scan(path string, q Query) (Result, error) {
q.Limit = ClampLimit(q.Limit, MaxLimit)
q.Offset = ClampOffset(q.Offset)
res := Result{Events: []map[string]any{}}
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return res, nil
}
return res, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return res, err
}
res.FileExists = true
res.FileSize = info.Size()
// For very large files, scan only the tail; the newest matches live there.
start := int64(0)
if info.Size() > scanBudget {
start = info.Size() - scanBudget
if _, err := f.Seek(start, 0); err != nil {
return res, err
}
res.Truncated = true
}
from, hasFrom := parseTime(q.From)
to, hasTo := parseTime(q.To)
keep := q.Offset + q.Limit
ring := make([]map[string]any, keep)
filled := 0
sc := bufio.NewScanner(f)
// Sanitized values are capped at 4096 bytes each; a record with many
// fields stays well under 1 MB. Allow headroom rather than aborting the
// whole query on one long line.
sc.Buffer(make([]byte, 64*1024), 4*1024*1024)
first := true
for sc.Scan() {
line := sc.Text()
if start > 0 && first {
// Seeking into the middle of the file lands mid-line. Drop that
// partial record.
first = false
continue
}
first = false
res.ScannedBytes += int64(len(line)) + 1
line = strings.TrimSpace(line)
if line == "" {
continue
}
var rec map[string]any
if err := json.Unmarshal([]byte(line), &rec); err != nil {
continue // tolerate a torn line instead of failing the page
}
if _, ok := rec["event"].(string); !ok {
continue
}
// Only audit records belong in the result. The dedicated file contains
// nothing else, but a hand-edited or mixed file must not surface
// ordinary operational lines here.
if rec["audit"] != true {
continue
}
res.TotalAll++
if !recordMatches(rec, line, q, from, hasFrom, to, hasTo) {
continue
}
// Ring buffer of the last `keep` matches (file order is chronological).
ring[res.Total%keep] = rec
if filled < keep {
filled++
}
res.Total++
}
if err := sc.Err(); err != nil {
return res, err
}
// Newest first, skipping Offset. The match with 0-based index i lives at
// ring[i%keep] as long as i >= Total-filled.
for i := res.Total - 1 - q.Offset; i >= 0 && i >= res.Total-filled; i-- {
res.Events = append(res.Events, ring[i%keep])
if len(res.Events) >= q.Limit {
break
}
}
return res, nil
}
// recordMatches applies the non-time and time filters to one record. line is
// the raw JSON line, used for the keyword substring search.
func recordMatches(rec map[string]any, line string, q Query, from time.Time, hasFrom bool, to time.Time, hasTo bool) bool {
if q.Event != "" && !eventFilterMatches(q.Event, StringField(rec, "event")) {
return false
}
if q.EventContains != "" && !strings.Contains(strings.ToLower(StringField(rec, "event")), strings.ToLower(q.EventContains)) {
return false
}
if q.Actor != "" && !strings.EqualFold(StringField(rec, "actor"), q.Actor) {
return false
}
if q.IP != "" && StringField(rec, "ip") != q.IP {
return false
}
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
}
if q.Keyword != "" && !strings.Contains(strings.ToLower(line), strings.ToLower(q.Keyword)) {
return false
}
if hasFrom || hasTo {
t, ok := parseTime(StringField(rec, "time"))
if !ok {
return false // cannot prove it is in range
}
if hasFrom && t.Before(from) {
return false
}
if hasTo && t.After(to) {
return false
}
}
return true
}
// eventFilterMatches supports three forms so the UI stays simple:
//
// "web.login.failure" exact
// "web.*" prefix (trailing "*")
// "web." prefix (trailing ".")
func eventFilterMatches(filter, event string) bool {
switch {
case strings.HasSuffix(filter, "*"):
return strings.HasPrefix(event, strings.TrimSuffix(filter, "*"))
case strings.HasSuffix(filter, "."):
return strings.HasPrefix(event, filter)
default:
return event == filter
}
}
// 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)
return s
}
// parseTime accepts the formats operators and browsers realistically send.
// Layouts without an explicit zone are parsed as UTC; the frontend always sends
// Date.toISOString(), so the RFC3339 path is what production uses.
func parseTime(s string) (time.Time, bool) {
s = strings.TrimSpace(s)
if s == "" {
return time.Time{}, false
}
layouts := []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02T15:04:05",
"2006-01-02T15:04",
"2006-01-02 15:04:05",
"2006-01-02",
}
for _, layout := range layouts {
if t, err := time.Parse(layout, s); err == nil {
return t, true
}
}
return time.Time{}, false
}