Feature(Go): four local MCP read tools and a shared audit query package
Implement milestone M2 of the minimal MCP plan: the tools that answer from the server's own state instead of opening a device channel. - Extract the audit-log scanner from web into package auditquery so the admin page and get_audit_log share one implementation. The web handler keeps its 500-row cap, the MCP tool uses the protocol's 1000-row cap. Query gains json tags for the web snake_case wire format (device_id, warn_only) and reports TotalAll before filters. - Add package buildinfo and inject Version/Commit with -X from build.ps1 and the Makefile; go-winres refreshes Windows resources from the git tag when available. An unversioned build reports "", and only initialize substitutes "dev". - list_hosts: online/offline pools, include_offline merge, every documented filter, limit/offset paging with total/totalAll/hasMore, and schema-named host fields (authStatus/tls/remark are never fabricated). - get_host_detail: single id or a batch of up to 50, online lookup then the last history record, capabilities from protocol.SupportsCap plus the Windows/registry/virtual-desktop rules; v2 is not listed. - get_server_status: version, uptime, online/offline counts, port and bind. sessions stays absent until the MCP session table lands in M3. - get_audit_log: case-insensitive event substring, keyword, paging; hasMore turns false at the MaxOffset clamp so paging cannot loop. Wire hub, history, audit path and listen address through mcp.Config from cmd/main.go. Tests cover pools/filters/paging, capability bits, batch failures, audit paging and the unversioned build. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
3f1957a9c9
commit
774c0d2545
16 files changed
+1952
-449
No files matched your search
@@ -95,6 +95,7 @@ server/go/web/assets/index.html
|
|||||||
server/go/users.json
|
server/go/users.json
|
||||||
server/go/devices.json
|
server/go/devices.json
|
||||||
server/go/build/
|
server/go/build/
|
||||||
|
server/go/cmd/*.syso
|
||||||
server/go/.claude/settings.json
|
server/go/.claude/settings.json
|
||||||
android/app/.cxx/
|
android/app/.cxx/
|
||||||
|
|
||||||
|
|||||||
@@ -74,8 +74,28 @@ function Build-GoServer {
|
|||||||
} else {
|
} else {
|
||||||
Join-Path $binDir "YamaGo_x64.exe"
|
Join-Path $binDir "YamaGo_x64.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Version/commit metadata injected into serverInfo and get_server_status.
|
||||||
|
# Empty when git is unavailable (source tarball, IDE build) — the server
|
||||||
|
# then reports no version rather than a fabricated one.
|
||||||
|
$gitVersion = ""
|
||||||
|
$gitCommit = ""
|
||||||
|
if (Get-Command git -ErrorAction SilentlyContinue) {
|
||||||
|
$gitVersion = (& git -C $rootDir describe --tags --always --dirty 2>$null | Select-Object -First 1)
|
||||||
|
if ($LASTEXITCODE -ne 0 -or -not $gitVersion) { $gitVersion = "" } else { $gitVersion = "$gitVersion".Trim() }
|
||||||
|
$gitCommit = (& git -C $rootDir rev-parse --short HEAD 2>$null | Select-Object -First 1)
|
||||||
|
if ($LASTEXITCODE -ne 0 -or -not $gitCommit) { $gitCommit = "" } else { $gitCommit = "$gitCommit".Trim() }
|
||||||
|
}
|
||||||
|
$buildinfoPkg = "github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo"
|
||||||
|
$ldflagParts = @()
|
||||||
# Release strips debug info for smaller binary; Debug keeps symbols.
|
# Release strips debug info for smaller binary; Debug keeps symbols.
|
||||||
$ldflags = if ($Configuration -eq "Debug") { "" } else { "-s -w" }
|
if ($Configuration -ne "Debug") { $ldflagParts += @("-s", "-w") }
|
||||||
|
if ($gitVersion) { $ldflagParts += @("-X", "$buildinfoPkg.Version=$gitVersion") }
|
||||||
|
if ($gitCommit) { $ldflagParts += @("-X", "$buildinfoPkg.Commit=$gitCommit") }
|
||||||
|
$ldflags = $ldflagParts -join " "
|
||||||
|
if ($gitVersion) {
|
||||||
|
Write-Host "Version: $gitVersion ($gitCommit)" -ForegroundColor DarkGray
|
||||||
|
}
|
||||||
|
|
||||||
# Save the caller's Go env so a direct .\build.ps1 invocation does not
|
# Save the caller's Go env so a direct .\build.ps1 invocation does not
|
||||||
# leave GOOS=linux behind for later builds in the same shell.
|
# leave GOOS=linux behind for later builds in the same shell.
|
||||||
@@ -90,6 +110,21 @@ function Build-GoServer {
|
|||||||
# Cross-compiling for Linux requires a pure-Go build; the server has
|
# Cross-compiling for Linux requires a pure-Go build; the server has
|
||||||
# no cgo dependencies, so this is the normal configuration.
|
# no cgo dependencies, so this is the normal configuration.
|
||||||
if ($TargetOS -eq "linux") { $env:CGO_ENABLED = "0" }
|
if ($TargetOS -eq "linux") { $env:CGO_ENABLED = "0" }
|
||||||
|
# Refresh the Windows resources before linking: go-winres rewrites the
|
||||||
|
# manifest identity, FileVersion and ProductVersion from the git tag so
|
||||||
|
# Explorer's file properties match the tag while the runtime version
|
||||||
|
# string stays the full `git describe` output. Missing go-winres or a
|
||||||
|
# non-git tree keeps the checked-in .syso files unchanged.
|
||||||
|
if ($TargetOS -eq "windows" -and $gitVersion) {
|
||||||
|
if (Get-Command go-winres -ErrorAction SilentlyContinue) {
|
||||||
|
& go-winres make --in cmd/winres/winres.json --out cmd/rsrc --product-version git-tag --file-version git-tag
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host "WARNING: go-winres failed; keeping existing cmd/rsrc_*.syso" -ForegroundColor Yellow
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Write-Host "WARNING: go-winres not found; version resources not refreshed (go install github.com/tc-hib/go-winres@latest)" -ForegroundColor Yellow
|
||||||
|
}
|
||||||
|
}
|
||||||
if ($ldflags) {
|
if ($ldflags) {
|
||||||
& go build -ldflags $ldflags -o $outFile ./cmd
|
& go build -ldflags $ldflags -o $outFile ./cmd
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -145,7 +145,8 @@
|
|||||||
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。
|
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。
|
||||||
|
|
||||||
`hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/
|
`hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/
|
||||||
screen/online/last_seen`;hub 没有 `authStatus/tls/location/install_time/remark`,不出现。
|
screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`;两个服务端都
|
||||||
|
没有 `authStatus/tls/remark`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。
|
||||||
|
|
||||||
#### `get_host_detail`
|
#### `get_host_detail`
|
||||||
|
|
||||||
|
|||||||
@@ -196,7 +196,8 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
|
|||||||
- `list_hosts`:`hub.ListDevices()` + `history.Offline(onlineSet)` 合并;`include_offline`
|
- `list_hosts`:`hub.ListDevices()` + `history.Offline(onlineSet)` 合并;`include_offline`
|
||||||
决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query`
|
决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query`
|
||||||
大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`,
|
大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`,
|
||||||
host 字段按 schema 命名组装,hub 没有的(`authStatus/tls/location/install_time/remark`)不伪造。
|
host 字段按 schema 命名组装,hub/历史里确有的 `location/install_time/screen/version` 照填,
|
||||||
|
两边都没有的 `authStatus/tls/remark` 不伪造。
|
||||||
- `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`);
|
- `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`);
|
||||||
`capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}`
|
`capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}`
|
||||||
(`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。
|
(`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。
|
||||||
|
|||||||
+9
-2
@@ -10,8 +10,15 @@ BUILD_DIR=build
|
|||||||
# Main package path
|
# Main package path
|
||||||
MAIN_PACKAGE=./cmd
|
MAIN_PACKAGE=./cmd
|
||||||
|
|
||||||
# Go build flags (strip debug info for smaller binary)
|
# Version metadata injected at link time (see buildinfo package). Both are
|
||||||
LDFLAGS=-ldflags "-s -w"
|
# empty outside a git checkout; the server then reports no version rather than
|
||||||
|
# a fabricated one.
|
||||||
|
VERSION := $(shell git describe --tags --always --dirty 2>nul)
|
||||||
|
COMMIT := $(shell git rev-parse --short HEAD 2>nul)
|
||||||
|
BUILDINFO_PKG = github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo
|
||||||
|
|
||||||
|
# Go build flags (strip debug info for smaller binary; version always injected)
|
||||||
|
LDFLAGS=-ldflags "-s -w -X $(BUILDINFO_PKG).Version=$(VERSION) -X $(BUILDINFO_PKG).Commit=$(COMMIT)"
|
||||||
|
|
||||||
# Windows commands
|
# Windows commands
|
||||||
MKDIR=if not exist $(BUILD_DIR) mkdir $(BUILD_DIR)
|
MKDIR=if not exist $(BUILD_DIR) mkdir $(BUILD_DIR)
|
||||||
|
|||||||
@@ -0,0 +1,287 @@
|
|||||||
|
// 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
|
||||||
|
|
||||||
|
// 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.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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
package auditquery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// writeAuditFixture writes JSON-lines audit records (oldest first) and returns
|
||||||
|
// the file path. Times are UTC RFC3339 so the tests are timezone-independent.
|
||||||
|
func writeAuditFixture(t *testing.T, records []map[string]any) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(t.TempDir(), "audit.log")
|
||||||
|
var b strings.Builder
|
||||||
|
for _, rec := range records {
|
||||||
|
line, err := json.Marshal(rec)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal fixture: %v", err)
|
||||||
|
}
|
||||||
|
b.Write(line)
|
||||||
|
b.WriteByte('\n')
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
|
||||||
|
t.Fatalf("write fixture: %v", err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func auditFixtureRecords() []map[string]any {
|
||||||
|
at := func(hhmm string) string {
|
||||||
|
tm, err := time.Parse("2006-01-02T15:04", "2026-10-18T"+hhmm)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return tm.Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
return []map[string]any{
|
||||||
|
{"level": "info", "time": at("10:00"), "audit": true, "event": "web.login.success", "actor": "admin", "ip": "203.0.113.1"},
|
||||||
|
{"level": "warn", "time": at("10:01"), "audit": true, "event": "web.login.failure", "actor": "alice", "ip": "203.0.113.2", "reason": "invalid_credentials"},
|
||||||
|
{"level": "info", "time": at("10:02"), "audit": true, "event": "remote.screen.start", "actor": "admin", "role": "admin", "ip": "203.0.113.1", "device_id": "dev1"},
|
||||||
|
{"level": "info", "time": at("10:03"), "audit": true, "event": "admin.user.delete", "actor": "admin", "ip": "203.0.113.1", "target": "bob"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runAuditQuery(t *testing.T, path string, q Query) Result {
|
||||||
|
t.Helper()
|
||||||
|
q.Limit = ClampLimit(q.Limit, MaxLimit)
|
||||||
|
q.Offset = ClampOffset(q.Offset)
|
||||||
|
res, err := Scan(path, q)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Scan: %v", err)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func eventNames(res Result) []string {
|
||||||
|
out := make([]string, 0, len(res.Events))
|
||||||
|
for _, e := range res.Events {
|
||||||
|
out = append(out, StringField(e, "event"))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNoFilterNewestFirst(t *testing.T) {
|
||||||
|
path := writeAuditFixture(t, auditFixtureRecords())
|
||||||
|
res := runAuditQuery(t, path, Query{Limit: 100})
|
||||||
|
if res.Total != 4 || len(res.Events) != 4 {
|
||||||
|
t.Fatalf("total=%d events=%d, want 4/4", res.Total, len(res.Events))
|
||||||
|
}
|
||||||
|
if res.TotalAll != 4 {
|
||||||
|
t.Fatalf("totalAll=%d, want 4", res.TotalAll)
|
||||||
|
}
|
||||||
|
got := eventNames(res)
|
||||||
|
want := []string{"admin.user.delete", "remote.screen.start", "web.login.failure", "web.login.success"}
|
||||||
|
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||||
|
t.Fatalf("events = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEventFilters(t *testing.T) {
|
||||||
|
path := writeAuditFixture(t, auditFixtureRecords())
|
||||||
|
cases := []struct {
|
||||||
|
filter string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"web.", []string{"web.login.failure", "web.login.success"}},
|
||||||
|
{"web.*", []string{"web.login.failure", "web.login.success"}},
|
||||||
|
{"web.login.failure", []string{"web.login.failure"}},
|
||||||
|
{"remote.*", []string{"remote.screen.start"}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
res := runAuditQuery(t, path, Query{Event: tc.filter, Limit: 100})
|
||||||
|
got := eventNames(res)
|
||||||
|
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||||
|
t.Errorf("filter %q → %v, want %v", tc.filter, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEventContainsFilter(t *testing.T) {
|
||||||
|
path := writeAuditFixture(t, auditFixtureRecords())
|
||||||
|
res := runAuditQuery(t, path, Query{EventContains: "LOGIN", Limit: 100})
|
||||||
|
got := eventNames(res)
|
||||||
|
want := []string{"web.login.failure", "web.login.success"}
|
||||||
|
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||||
|
t.Fatalf("events = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
// Filters run before paging: total reflects matches, totalAll the window.
|
||||||
|
if res.Total != 2 || res.TotalAll != 4 {
|
||||||
|
t.Fatalf("total=%d totalAll=%d, want 2/4", res.Total, res.TotalAll)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFieldFilters(t *testing.T) {
|
||||||
|
path := writeAuditFixture(t, auditFixtureRecords())
|
||||||
|
from, _ := time.Parse(time.RFC3339, "2026-10-18T10:01:00Z")
|
||||||
|
to, _ := time.Parse(time.RFC3339, "2026-10-18T10:02:00Z")
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
q Query
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"actor case-insensitive", Query{Actor: "ALICE", Limit: 100}, []string{"web.login.failure"}},
|
||||||
|
{"ip", Query{IP: "203.0.113.2", Limit: 100}, []string{"web.login.failure"}},
|
||||||
|
{"device", Query{DeviceID: "dev1", Limit: 100}, []string{"remote.screen.start"}},
|
||||||
|
{"warn only", Query{WarnOnly: true, Limit: 100}, []string{"web.login.failure"}},
|
||||||
|
{"keyword target", Query{Keyword: "BOB", Limit: 100}, []string{"admin.user.delete"}},
|
||||||
|
{"time range", Query{
|
||||||
|
From: from.Format(time.RFC3339), To: to.Format(time.RFC3339), Limit: 100,
|
||||||
|
}, []string{"remote.screen.start", "web.login.failure"}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
res := runAuditQuery(t, path, tc.q)
|
||||||
|
got := eventNames(res)
|
||||||
|
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||||
|
t.Errorf("%s → %v, want %v", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOffsetAndLimit(t *testing.T) {
|
||||||
|
path := writeAuditFixture(t, auditFixtureRecords())
|
||||||
|
res := runAuditQuery(t, path, Query{Limit: 2, Offset: 1})
|
||||||
|
if res.Total != 4 {
|
||||||
|
t.Fatalf("total = %d, want 4", res.Total)
|
||||||
|
}
|
||||||
|
got := eventNames(res)
|
||||||
|
want := []string{"remote.screen.start", "web.login.failure"}
|
||||||
|
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||||
|
t.Fatalf("events = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Offsetting past the end yields no events but keeps the total.
|
||||||
|
res = runAuditQuery(t, path, Query{Limit: 2, Offset: 4})
|
||||||
|
if res.Total != 4 || len(res.Events) != 0 {
|
||||||
|
t.Fatalf("offset past end: total=%d events=%v", res.Total, eventNames(res))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSkipsNonAuditAndTornLines(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "audit.log")
|
||||||
|
content := `{"event":"device.online","actor":"x"}
|
||||||
|
not json at all
|
||||||
|
{"level":"info","time":"2026-10-18T10:00:00Z","audit":true,"event":"web.login.success","actor":"admin"}`
|
||||||
|
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res := runAuditQuery(t, path, Query{Limit: 100})
|
||||||
|
if res.Total != 1 || len(res.Events) != 1 {
|
||||||
|
t.Fatalf("total=%d events=%v, want the single valid record", res.Total, eventNames(res))
|
||||||
|
}
|
||||||
|
// Non-audit and torn lines do not count toward totalAll either.
|
||||||
|
if res.TotalAll != 1 {
|
||||||
|
t.Fatalf("totalAll=%d, want 1", res.TotalAll)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingFile(t *testing.T) {
|
||||||
|
res := runAuditQuery(t, filepath.Join(t.TempDir(), "does-not-exist.log"), Query{Limit: 10})
|
||||||
|
if res.FileExists {
|
||||||
|
t.Error("FileExists = true for a missing file")
|
||||||
|
}
|
||||||
|
if res.Total != 0 || len(res.Events) != 0 {
|
||||||
|
t.Errorf("total=%d events=%v, want empty", res.Total, eventNames(res))
|
||||||
|
}
|
||||||
|
if res.Events == nil {
|
||||||
|
t.Error("Events is nil; JSON would encode null instead of []")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClampsPaging(t *testing.T) {
|
||||||
|
if got := ClampLimit(0, MaxLimit); got != DefaultLimit {
|
||||||
|
t.Errorf("limit(0) = %d, want default %d", got, DefaultLimit)
|
||||||
|
}
|
||||||
|
if got := ClampLimit(-3, MaxLimit); got != DefaultLimit {
|
||||||
|
t.Errorf("limit(-3) = %d, want default %d", got, DefaultLimit)
|
||||||
|
}
|
||||||
|
if got := ClampLimit(9999, MaxLimit); got != MaxLimit {
|
||||||
|
t.Errorf("limit(9999) = %d, want max %d", got, MaxLimit)
|
||||||
|
}
|
||||||
|
if got := ClampLimit(9999, 500); got != 500 {
|
||||||
|
t.Errorf("limit(9999, max 500) = %d, want 500", got)
|
||||||
|
}
|
||||||
|
if got := ClampLimit(50, MaxLimit); got != 50 {
|
||||||
|
t.Errorf("limit(50) = %d, want 50", got)
|
||||||
|
}
|
||||||
|
if got := ClampLimit(0, 0); got != DefaultLimit {
|
||||||
|
t.Errorf("limit(0, max 0) = %d, want default %d", got, DefaultLimit)
|
||||||
|
}
|
||||||
|
if got := ClampOffset(-5); got != 0 {
|
||||||
|
t.Errorf("offset(-5) = %d, want 0", got)
|
||||||
|
}
|
||||||
|
if got := ClampOffset(1 << 30); got != MaxOffset {
|
||||||
|
t.Errorf("offset(huge) = %d, want max %d", got, MaxOffset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The web audit page sends snake_case keys. Query is decoded from that wire
|
||||||
|
// format in web/audit_query.go, so the tags must keep those names — otherwise
|
||||||
|
// device_id / warn_only silently stop filtering.
|
||||||
|
func TestQueryDecodesWebWireFormat(t *testing.T) {
|
||||||
|
body := `{"from":"2026-11-01T00:00:00Z","to":"2026-11-12T00:00:00Z",` +
|
||||||
|
`"event":"web.","actor":"admin","ip":"1.2.3.4","device_id":"1001",` +
|
||||||
|
`"keyword":"k","warn_only":true,"limit":5,"offset":2}`
|
||||||
|
var q Query
|
||||||
|
if err := json.Unmarshal([]byte(body), &q); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
if q.From != "2026-11-01T00:00:00Z" || q.To != "2026-11-12T00:00:00Z" {
|
||||||
|
t.Fatalf("time range = %q..%q", q.From, q.To)
|
||||||
|
}
|
||||||
|
if q.Event != "web." || q.Actor != "admin" || q.IP != "1.2.3.4" {
|
||||||
|
t.Fatalf("filters = %+v", q)
|
||||||
|
}
|
||||||
|
if q.DeviceID != "1001" {
|
||||||
|
t.Fatalf("device_id = %q, want 1001", q.DeviceID)
|
||||||
|
}
|
||||||
|
if q.Keyword != "k" || !q.WarnOnly {
|
||||||
|
t.Fatalf("keyword/warn_only = %q/%v", q.Keyword, q.WarnOnly)
|
||||||
|
}
|
||||||
|
if q.Limit != 5 || q.Offset != 2 {
|
||||||
|
t.Fatalf("limit/offset = %d/%d", q.Limit, q.Offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// Package buildinfo exposes the version metadata injected at link time.
|
||||||
|
//
|
||||||
|
// Version and Commit are set by the build scripts with
|
||||||
|
//
|
||||||
|
// go build -ldflags "-X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Version=... \
|
||||||
|
// -X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Commit=..."
|
||||||
|
//
|
||||||
|
// They stay empty when the binary is built without git (source tarball, IDE
|
||||||
|
// run). Callers must report the empty string rather than inventing a value;
|
||||||
|
// only the MCP initialize response substitutes a literal "dev" marker.
|
||||||
|
package buildinfo
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Version is the full `git describe --tags --always --dirty` string, e.g.
|
||||||
|
// "v1.4.2-72-g425d737-dirty".
|
||||||
|
Version = ""
|
||||||
|
// Commit is the short commit hash, e.g. "425d737".
|
||||||
|
Commit = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
// Info is a JSON-friendly snapshot of the injected metadata.
|
||||||
|
type Info struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Commit string `json:"commit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot returns the current build metadata. It is safe to call before the
|
||||||
|
// values are injected (both fields are empty).
|
||||||
|
func Snapshot() Info {
|
||||||
|
return Info{Version: Version, Commit: Commit}
|
||||||
|
}
|
||||||
+14
-3
@@ -17,6 +17,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auth"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auth"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
@@ -1302,20 +1303,30 @@ func main() {
|
|||||||
// MCP endpoint: a static bearer token independent of the web login. An
|
// MCP endpoint: a static bearer token independent of the web login. An
|
||||||
// empty YAMA_MCP_TOKEN leaves /mcp unregistered (404) — there is no
|
// empty YAMA_MCP_TOKEN leaves /mcp unregistered (404) — there is no
|
||||||
// auto-generated token, because a secret that only appears in a log is not
|
// auto-generated token, because a secret that only appears in a log is not
|
||||||
// a secret. Version wiring arrives with the buildinfo package; until then
|
// a secret. Version/commit come from the link-time buildinfo injection.
|
||||||
// initialize reports "dev".
|
|
||||||
mcpReadonly := envBool("YAMA_MCP_READONLY")
|
mcpReadonly := envBool("YAMA_MCP_READONLY")
|
||||||
|
bindAddr := ""
|
||||||
|
if *httpPort != 0 {
|
||||||
|
bindAddr = "0.0.0.0" // web server listens on :port (all interfaces)
|
||||||
|
}
|
||||||
mcpSrv := mcp.New(mcp.Config{
|
mcpSrv := mcp.New(mcp.Config{
|
||||||
Token: strings.TrimSpace(os.Getenv("YAMA_MCP_TOKEN")),
|
Token: strings.TrimSpace(os.Getenv("YAMA_MCP_TOKEN")),
|
||||||
Readonly: mcpReadonly,
|
Readonly: mcpReadonly,
|
||||||
TermIdle: time.Duration(envInt("YAMA_MCP_TERM_IDLE", 180)) * time.Second,
|
TermIdle: time.Duration(envInt("YAMA_MCP_TERM_IDLE", 180)) * time.Second,
|
||||||
MaxConcurrency: envInt("YAMA_MCP_MAX_CONCURRENCY", 16),
|
MaxConcurrency: envInt("YAMA_MCP_MAX_CONCURRENCY", 16),
|
||||||
ReadMax: int64(envInt("YAMA_MCP_READ_MAX", 2<<20)),
|
ReadMax: int64(envInt("YAMA_MCP_READ_MAX", 2<<20)),
|
||||||
|
Version: buildinfo.Version,
|
||||||
StartedAt: time.Now(),
|
StartedAt: time.Now(),
|
||||||
Log: log.WithPrefix("MCP"),
|
Log: log.WithPrefix("MCP"),
|
||||||
|
Hub: deviceHub,
|
||||||
|
History: deviceHistory,
|
||||||
|
AuditPath: auditFile,
|
||||||
|
Port: *httpPort,
|
||||||
|
Bind: bindAddr,
|
||||||
})
|
})
|
||||||
if mcpSrv.Enabled() {
|
if mcpSrv.Enabled() {
|
||||||
log.Info("MCP endpoint enabled on /mcp (readonly=%v)", mcpReadonly)
|
log.Info("MCP endpoint enabled on /mcp (readonly=%v, commit=%s)",
|
||||||
|
mcpReadonly, buildinfo.Commit)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start HTTP server for web UI. Hub gives it read-only access to the
|
// Start HTTP server for web UI. Hub gives it read-only access to the
|
||||||
|
|||||||
+25
-5
@@ -11,6 +11,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -39,6 +41,15 @@ type Config struct {
|
|||||||
Version string // serverInfo.version
|
Version string // serverInfo.version
|
||||||
StartedAt time.Time // reported by get_server_status
|
StartedAt time.Time // reported by get_server_status
|
||||||
Log *logger.Logger
|
Log *logger.Logger
|
||||||
|
|
||||||
|
// Server-side state the local read tools answer from. A nil Hub means the
|
||||||
|
// endpoint was built without a device registry: the host tools then fail
|
||||||
|
// with -32000 instead of reporting an empty (and misleading) list.
|
||||||
|
Hub *hub.Hub
|
||||||
|
History *devicehistory.Store // nil: no offline history to merge
|
||||||
|
AuditPath string // "" = audit file disabled (YAMA_AUDIT_LOG=off)
|
||||||
|
Port int // web/MCP listening port, for get_server_status
|
||||||
|
Bind string // listening address, for get_server_status
|
||||||
}
|
}
|
||||||
|
|
||||||
// toolFunc implements one tools/call. It returns either a result value or a
|
// toolFunc implements one tools/call. It returns either a result value or a
|
||||||
@@ -69,18 +80,21 @@ func New(cfg Config) *Server {
|
|||||||
if cfg.StartedAt.IsZero() {
|
if cfg.StartedAt.IsZero() {
|
||||||
cfg.StartedAt = time.Now()
|
cfg.StartedAt = time.Now()
|
||||||
}
|
}
|
||||||
if cfg.Version == "" {
|
// Version is left exactly as injected: it may be empty in a build without
|
||||||
cfg.Version = "dev"
|
// git/ldflags. The initialize response substitutes "dev" for such builds;
|
||||||
}
|
// get_server_status reports the empty string rather than inventing a
|
||||||
|
// version (design §3.2).
|
||||||
if cfg.Log == nil {
|
if cfg.Log == nil {
|
||||||
cfg.Log = logger.New(logger.Config{Level: logger.LevelError})
|
cfg.Log = logger.New(logger.Config{Level: logger.LevelError})
|
||||||
}
|
}
|
||||||
return &Server{
|
s := &Server{
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
log: cfg.Log,
|
log: cfg.Log,
|
||||||
tools: buildToolSet(toolsJSON),
|
tools: buildToolSet(toolsJSON),
|
||||||
handlers: make(map[string]toolFunc),
|
handlers: make(map[string]toolFunc),
|
||||||
}
|
}
|
||||||
|
s.registerLocalTools()
|
||||||
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enabled reports whether /mcp should be registered. An empty token disables
|
// Enabled reports whether /mcp should be registered. An empty token disables
|
||||||
@@ -203,10 +217,16 @@ type initializeResult struct {
|
|||||||
// serverInfo.name ("yama") so clients do not special-case the Go backend.
|
// serverInfo.name ("yama") so clients do not special-case the Go backend.
|
||||||
// Differences are stated in instructions, which models read.
|
// Differences are stated in instructions, which models read.
|
||||||
func (s *Server) initializeResult() initializeResult {
|
func (s *Server) initializeResult() initializeResult {
|
||||||
|
// "dev" is a serverInfo-only marker for an unversioned build; the status
|
||||||
|
// tool keeps the raw (empty) value.
|
||||||
|
version := s.cfg.Version
|
||||||
|
if version == "" {
|
||||||
|
version = "dev"
|
||||||
|
}
|
||||||
return initializeResult{
|
return initializeResult{
|
||||||
ProtocolVersion: protocolVersion,
|
ProtocolVersion: protocolVersion,
|
||||||
Capabilities: serverCapabilities{Tools: toolsCapability{ListChanged: false}},
|
Capabilities: serverCapabilities{Tools: toolsCapability{ListChanged: false}},
|
||||||
ServerInfo: serverInfo{Name: "yama", Version: s.cfg.Version},
|
ServerInfo: serverInfo{Name: "yama", Version: version},
|
||||||
Instructions: serverInstructions,
|
Instructions: serverInstructions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -370,7 +370,9 @@ func TestToolsCallGates(t *testing.T) {
|
|||||||
code: CodeInvalidParams,
|
code: CodeInvalidParams,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "known but not implemented in M1",
|
// testServer has no hub: the handler exists (M2) and must fail
|
||||||
|
// loudly rather than report an empty device list.
|
||||||
|
name: "local tool without device registry",
|
||||||
srv: s,
|
srv: s,
|
||||||
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_hosts"}}`,
|
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_hosts"}}`,
|
||||||
code: CodeInternal,
|
code: CodeInternal,
|
||||||
|
|||||||
@@ -0,0 +1,590 @@
|
|||||||
|
package mcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Local read tools: they answer from the server's own state (device hub,
|
||||||
|
// device history, audit file) and never open a channel to a client. The
|
||||||
|
// remote tools (screenshot, files, terminal) live in later milestones.
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Page size bounds shared by list_hosts and get_audit_log, matching the
|
||||||
|
// tool descriptions in mcp/tools.json.
|
||||||
|
listDefaultLimit = 100
|
||||||
|
listMaxLimit = 1000
|
||||||
|
|
||||||
|
// batchMaxIDs is the per-call cap for get_host_detail.ids, matching the
|
||||||
|
// Win32 server.
|
||||||
|
batchMaxIDs = 50
|
||||||
|
)
|
||||||
|
|
||||||
|
// toolResult is the MCP tools/call success envelope, byte-compatible with the
|
||||||
|
// Win32 server: one text item plus structuredContent. Failures are JSON-RPC
|
||||||
|
// error objects at the top level, not isError results.
|
||||||
|
type toolResult struct {
|
||||||
|
Content []contentItem `json:"content"`
|
||||||
|
StructuredContent any `json:"structuredContent"`
|
||||||
|
IsError bool `json:"isError"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type contentItem struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func newToolResult(text string, structured any) toolResult {
|
||||||
|
return toolResult{
|
||||||
|
Content: []contentItem{{Type: "text", Text: text}},
|
||||||
|
StructuredContent: structured,
|
||||||
|
IsError: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) registerLocalTools() {
|
||||||
|
s.handlers["list_hosts"] = s.callListHosts
|
||||||
|
s.handlers["get_host_detail"] = s.callGetHostDetail
|
||||||
|
s.handlers["get_server_status"] = s.callGetServerStatus
|
||||||
|
s.handlers["get_audit_log"] = s.callGetAuditLog
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeArgs unmarshals tools/call arguments into v. An absent/null arguments
|
||||||
|
// object leaves v at its zero value, which is valid for the all-optional tools.
|
||||||
|
func decodeArgs(raw json.RawMessage, v any) *rpcError {
|
||||||
|
if len(raw) == 0 || string(raw) == "null" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, v); err != nil {
|
||||||
|
return errf(CodeInvalidParams, "invalid arguments: %v", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- list_hosts -----------------------------------------------------------
|
||||||
|
|
||||||
|
type listHostsArgs struct {
|
||||||
|
ClientType string `json:"client_type"`
|
||||||
|
Group string `json:"group"`
|
||||||
|
IncludeOffline *bool `json:"include_offline"`
|
||||||
|
IP string `json:"ip"`
|
||||||
|
Limit int `json:"limit"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Offset int `json:"offset"`
|
||||||
|
Online *bool `json:"online"`
|
||||||
|
OS string `json:"os"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||||
|
if s.cfg.Hub == nil {
|
||||||
|
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||||
|
}
|
||||||
|
var args listHostsArgs
|
||||||
|
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||||
|
return nil, rerr
|
||||||
|
}
|
||||||
|
|
||||||
|
// online defaults to true (only online hosts). online=false means "only
|
||||||
|
// offline"; include_offline=true merges history behind the online hosts.
|
||||||
|
online := true
|
||||||
|
if args.Online != nil {
|
||||||
|
online = *args.Online
|
||||||
|
}
|
||||||
|
includeOffline := args.IncludeOffline != nil && *args.IncludeOffline
|
||||||
|
|
||||||
|
onlineDevices := s.cfg.Hub.ListDevices()
|
||||||
|
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
||||||
|
for _, d := range onlineDevices {
|
||||||
|
onlineSet[d.ID] = struct{}{}
|
||||||
|
}
|
||||||
|
offlineDevices := s.offlineDevices(onlineSet)
|
||||||
|
|
||||||
|
var pool []hub.DeviceInfo
|
||||||
|
switch {
|
||||||
|
case !online:
|
||||||
|
pool = offlineDevices
|
||||||
|
case includeOffline:
|
||||||
|
pool = make([]hub.DeviceInfo, 0, len(onlineDevices)+len(offlineDevices))
|
||||||
|
pool = append(pool, onlineDevices...)
|
||||||
|
pool = append(pool, offlineDevices...)
|
||||||
|
default:
|
||||||
|
pool = onlineDevices
|
||||||
|
}
|
||||||
|
totalAll := len(pool)
|
||||||
|
|
||||||
|
// All filters are optional, ANDed, and substring matches. ASCII case
|
||||||
|
// folding is what the tool description promises; strings.ToLower is a
|
||||||
|
// superset and cannot change an ASCII-only match.
|
||||||
|
q := strings.ToLower(args.Query)
|
||||||
|
nameF := strings.ToLower(args.Name)
|
||||||
|
ipF := strings.ToLower(args.IP)
|
||||||
|
groupF := strings.ToLower(args.Group)
|
||||||
|
osF := strings.ToLower(args.OS)
|
||||||
|
ctF := strings.ToLower(args.ClientType)
|
||||||
|
|
||||||
|
matched := make([]hub.DeviceInfo, 0, len(pool))
|
||||||
|
for _, d := range pool {
|
||||||
|
group := d.Group
|
||||||
|
if group == "" {
|
||||||
|
group = "default"
|
||||||
|
}
|
||||||
|
ip := d.IP
|
||||||
|
if ip == "" {
|
||||||
|
ip = d.PeerIP
|
||||||
|
}
|
||||||
|
clientType := ""
|
||||||
|
if d.Online {
|
||||||
|
clientType = s.clientType(d.ID)
|
||||||
|
}
|
||||||
|
// query matches computer name, remark and IP. The two servers keep no
|
||||||
|
// remark column, so name+IP is the full set here.
|
||||||
|
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && !strings.Contains(strings.ToLower(ip), q) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if groupF != "" && !strings.Contains(strings.ToLower(group), groupF) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if osF != "" && !strings.Contains(strings.ToLower(d.OS), osF) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ctF != "" && !strings.Contains(strings.ToLower(clientType), ctF) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
matched = append(matched, d)
|
||||||
|
}
|
||||||
|
|
||||||
|
limit := clampPageLimit(args.Limit)
|
||||||
|
offset := max(args.Offset, 0)
|
||||||
|
total := len(matched)
|
||||||
|
begin := min(offset, total)
|
||||||
|
end := min(begin+limit, total)
|
||||||
|
hosts := make([]map[string]any, 0, end-begin)
|
||||||
|
for _, d := range matched[begin:end] {
|
||||||
|
hosts = append(hosts, s.hostJSON(d))
|
||||||
|
}
|
||||||
|
|
||||||
|
structured := map[string]any{
|
||||||
|
"hosts": hosts,
|
||||||
|
"total": total,
|
||||||
|
"totalAll": totalAll,
|
||||||
|
"limit": limit,
|
||||||
|
"offset": offset,
|
||||||
|
"hasMore": end < total,
|
||||||
|
}
|
||||||
|
text := pageSummary(total, limit, offset, "台主机")
|
||||||
|
if total != totalAll {
|
||||||
|
text += fmt.Sprintf("过滤前共 %d 台。", totalAll)
|
||||||
|
}
|
||||||
|
return newToolResult(text, structured), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// hostJSON projects a hub device onto the list_hosts/get_host_detail schema.
|
||||||
|
// Fields the Go server does not know (authStatus, tls, remark, clientType of
|
||||||
|
// an offline entry) are omitted rather than fabricated.
|
||||||
|
func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
|
||||||
|
group := d.Group
|
||||||
|
if group == "" {
|
||||||
|
group = "default"
|
||||||
|
}
|
||||||
|
h := map[string]any{
|
||||||
|
"id": d.ID,
|
||||||
|
"name": d.Name,
|
||||||
|
"group": group,
|
||||||
|
"online": d.Online,
|
||||||
|
}
|
||||||
|
if d.Version != "" {
|
||||||
|
h["version"] = d.Version
|
||||||
|
}
|
||||||
|
if d.OS != "" {
|
||||||
|
h["os"] = d.OS
|
||||||
|
}
|
||||||
|
ip := d.IP
|
||||||
|
if ip == "" {
|
||||||
|
ip = d.PeerIP
|
||||||
|
}
|
||||||
|
if ip != "" {
|
||||||
|
h["ip"] = ip
|
||||||
|
}
|
||||||
|
if d.Location != "" {
|
||||||
|
h["location"] = d.Location
|
||||||
|
}
|
||||||
|
if d.InstallTime != "" {
|
||||||
|
h["install_time"] = d.InstallTime
|
||||||
|
}
|
||||||
|
if d.Screen != "" {
|
||||||
|
h["screen"] = d.Screen
|
||||||
|
}
|
||||||
|
if d.Online {
|
||||||
|
// RTT 0 means "no heartbeat yet", not "zero latency".
|
||||||
|
if d.RTT > 0 {
|
||||||
|
h["rtt"] = strconv.Itoa(d.RTT)
|
||||||
|
}
|
||||||
|
if d.ActiveWindow != "" {
|
||||||
|
h["activeWindow"] = d.ActiveWindow
|
||||||
|
}
|
||||||
|
if ct := s.clientType(d.ID); ct != "" {
|
||||||
|
h["clientType"] = ct
|
||||||
|
}
|
||||||
|
} else if d.LastSeen > 0 {
|
||||||
|
h["last_seen"] = time.Unix(d.LastSeen, 0).Format("2006-01-02 15:04:05")
|
||||||
|
}
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
// clientType reads the RES_CLIENT_TYPE the client reported at login. It lives
|
||||||
|
// on the main connection's ClientInfo, not on the hub's Device projection.
|
||||||
|
func (s *Server) clientType(deviceID string) string {
|
||||||
|
if s.cfg.Hub == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if ctx := s.cfg.Hub.MainConn(deviceID); ctx != nil {
|
||||||
|
return ctx.GetInfo().ClientType
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// offlineDevices returns history entries that are not currently online. A nil
|
||||||
|
// history store (server started without persistence) yields no entries.
|
||||||
|
func (s *Server) offlineDevices(online map[string]struct{}) []hub.DeviceInfo {
|
||||||
|
if s.cfg.History == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.cfg.History.Offline(online)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- get_host_detail ------------------------------------------------------
|
||||||
|
|
||||||
|
type getHostDetailArgs struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
IDs []string `json:"ids"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||||
|
if s.cfg.Hub == nil {
|
||||||
|
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||||
|
}
|
||||||
|
var args getHostDetailArgs
|
||||||
|
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||||
|
return nil, rerr
|
||||||
|
}
|
||||||
|
if len(args.IDs) > 0 {
|
||||||
|
return s.hostDetailBatch(args.IDs)
|
||||||
|
}
|
||||||
|
if args.ID == "" {
|
||||||
|
return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids")
|
||||||
|
}
|
||||||
|
online, offline := s.hostMaps()
|
||||||
|
host, rerr := s.lookupHost(args.ID, online, offline)
|
||||||
|
if rerr != nil {
|
||||||
|
return nil, rerr
|
||||||
|
}
|
||||||
|
return newToolResult(hostSummary(host), map[string]any{"host": host}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
|
||||||
|
if len(ids) > batchMaxIDs {
|
||||||
|
return nil, errf(CodeInvalidParams,
|
||||||
|
"Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs)
|
||||||
|
}
|
||||||
|
online, offline := s.hostMaps()
|
||||||
|
results := make([]map[string]any, 0, len(ids))
|
||||||
|
succeeded, failed := 0, 0
|
||||||
|
for _, id := range ids {
|
||||||
|
host, rerr := s.lookupHost(id, online, offline)
|
||||||
|
if rerr != nil {
|
||||||
|
results = append(results, map[string]any{
|
||||||
|
"id": id,
|
||||||
|
"ok": false,
|
||||||
|
"text": rerr.Message,
|
||||||
|
"error": map[string]any{"code": rerr.Code, "message": rerr.Message},
|
||||||
|
})
|
||||||
|
failed++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
results = append(results, map[string]any{
|
||||||
|
"id": id,
|
||||||
|
"ok": true,
|
||||||
|
"text": hostSummary(host),
|
||||||
|
"data": map[string]any{"host": host},
|
||||||
|
})
|
||||||
|
succeeded++
|
||||||
|
}
|
||||||
|
structured := map[string]any{
|
||||||
|
"tool": "get_host_detail",
|
||||||
|
"total": len(ids),
|
||||||
|
"succeeded": succeeded,
|
||||||
|
"failed": failed,
|
||||||
|
"skipped": 0, // no batch deadline: every id is answered locally
|
||||||
|
"results": results,
|
||||||
|
}
|
||||||
|
text := fmt.Sprintf("批量调用 get_host_detail:共 %d 台,成功 %d 台,失败 %d 台。",
|
||||||
|
len(ids), succeeded, failed)
|
||||||
|
return newToolResult(text, structured), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// hostMaps indexes the online devices and offline history by ID. Building both
|
||||||
|
// once per call keeps a 50-id batch at one hub snapshot instead of 50.
|
||||||
|
func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
|
||||||
|
onlineDevices := s.cfg.Hub.ListDevices()
|
||||||
|
online = make(map[string]hub.DeviceInfo, len(onlineDevices))
|
||||||
|
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
||||||
|
for _, d := range onlineDevices {
|
||||||
|
online[d.ID] = d
|
||||||
|
onlineSet[d.ID] = struct{}{}
|
||||||
|
}
|
||||||
|
offlineDevices := s.offlineDevices(onlineSet)
|
||||||
|
offline = make(map[string]hub.DeviceInfo, len(offlineDevices))
|
||||||
|
for _, d := range offlineDevices {
|
||||||
|
offline[d.ID] = d
|
||||||
|
}
|
||||||
|
return online, offline
|
||||||
|
}
|
||||||
|
|
||||||
|
// lookupHost resolves one host: online first, then the last-known history
|
||||||
|
// record. It mirrors the Win32 server, which answers offline hosts with their
|
||||||
|
// final snapshot instead of an error.
|
||||||
|
func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo) (map[string]any, *rpcError) {
|
||||||
|
if !isDecimalID(id) {
|
||||||
|
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||||
|
}
|
||||||
|
if d, ok := online[id]; ok {
|
||||||
|
h := s.hostJSON(d)
|
||||||
|
h["capabilities"] = s.capabilities(d)
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
if d, ok := offline[id]; ok {
|
||||||
|
return s.hostJSON(d), nil
|
||||||
|
}
|
||||||
|
return nil, errf(CodeOffline, "Host not found or offline: %s", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// capabilities answers "what can this host do" from the capability hex string
|
||||||
|
// the client reported at login. v2 is deliberately absent: CLIENT_CAP_V2 is
|
||||||
|
// set by every platform, so listing it would only mislead.
|
||||||
|
func (s *Server) capabilities(d hub.DeviceInfo) map[string]any {
|
||||||
|
platform := s.clientType(d.ID)
|
||||||
|
windows := platform != "LNX" && platform != "MAC" && platform != "APK"
|
||||||
|
monitors := monitorCount(d.Screen)
|
||||||
|
// Multi-monitor Windows needs whole-virtual-desktop capture for the
|
||||||
|
// observed and injected coordinate spaces to line up; monitorCount 0
|
||||||
|
// means the client did not report the "N:W*H" form (legacy) and passes,
|
||||||
|
// matching the Win32 server's remote_open gate.
|
||||||
|
virtualDesktopOK := monitors <= 1 || !windows ||
|
||||||
|
protocol.SupportsCap(d.Capability, protocol.ClientCapVirtualDesktop)
|
||||||
|
caps := map[string]any{
|
||||||
|
"screenPreview": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenPreview),
|
||||||
|
"screenRegion": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenRegion),
|
||||||
|
"windowInfo": protocol.SupportsCap(d.Capability, protocol.ClientCapWindowInfo),
|
||||||
|
"fileTransferV2": protocol.SupportsCap(d.Capability, protocol.ClientCapV2),
|
||||||
|
"c2cPaths": protocol.SupportsCap(d.Capability, protocol.ClientCapC2CPaths),
|
||||||
|
"registry": windows,
|
||||||
|
"remoteControl": (windows || platform == "LNX" || platform == "APK") && virtualDesktopOK,
|
||||||
|
}
|
||||||
|
if platform != "" {
|
||||||
|
caps["platform"] = platform
|
||||||
|
}
|
||||||
|
return caps
|
||||||
|
}
|
||||||
|
|
||||||
|
// hostSummary is the human-readable text item for one host.
|
||||||
|
func hostSummary(h map[string]any) string {
|
||||||
|
name, _ := h["name"].(string)
|
||||||
|
ip, _ := h["ip"].(string)
|
||||||
|
if online, _ := h["online"].(bool); !online {
|
||||||
|
return fmt.Sprintf("主机 %s (%s) 当前离线,以下为其最后一次登录时的记录。", name, ip)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("主机 %s (%s) 的详情。", name, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- get_server_status ----------------------------------------------------
|
||||||
|
|
||||||
|
func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any, *rpcError) {
|
||||||
|
uptime := max(int64(time.Since(s.cfg.StartedAt).Seconds()), 0)
|
||||||
|
status := map[string]any{
|
||||||
|
"version": s.cfg.Version,
|
||||||
|
"uptime_sec": uptime,
|
||||||
|
}
|
||||||
|
text := fmt.Sprintf("YAMA Go 服务端已运行 %d 秒", uptime)
|
||||||
|
if s.cfg.Version != "" {
|
||||||
|
text = fmt.Sprintf("YAMA Go 服务端 %s 已运行 %d 秒", s.cfg.Version, uptime)
|
||||||
|
}
|
||||||
|
if s.cfg.Hub != nil {
|
||||||
|
onlineDevices := s.cfg.Hub.ListDevices()
|
||||||
|
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
||||||
|
for _, d := range onlineDevices {
|
||||||
|
onlineSet[d.ID] = struct{}{}
|
||||||
|
}
|
||||||
|
offline := len(s.offlineDevices(onlineSet))
|
||||||
|
status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline}
|
||||||
|
text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline)
|
||||||
|
}
|
||||||
|
// MCP is mounted on the web server, so its listening address is the web
|
||||||
|
// server's. Port/bind stay absent when the caller did not provide them.
|
||||||
|
if s.cfg.Port > 0 {
|
||||||
|
status["port"] = s.cfg.Port
|
||||||
|
}
|
||||||
|
if s.cfg.Bind != "" {
|
||||||
|
status["bind"] = s.cfg.Bind
|
||||||
|
text += ",监听 " + s.cfg.Bind
|
||||||
|
}
|
||||||
|
// The status fields are flat in structuredContent (the outputSchema has no
|
||||||
|
// "status" wrapper object).
|
||||||
|
return newToolResult(text+"。", status), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- get_audit_log --------------------------------------------------------
|
||||||
|
|
||||||
|
type getAuditLogArgs struct {
|
||||||
|
Keyword string `json:"keyword"`
|
||||||
|
Limit int `json:"limit"`
|
||||||
|
Offset int `json:"offset"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||||
|
if s.cfg.AuditPath == "" {
|
||||||
|
return nil, errf(CodeInternal,
|
||||||
|
"audit log file is disabled on this server (YAMA_AUDIT_LOG=off)")
|
||||||
|
}
|
||||||
|
var args getAuditLogArgs
|
||||||
|
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||||
|
return nil, rerr
|
||||||
|
}
|
||||||
|
q := auditquery.Query{
|
||||||
|
Keyword: args.Keyword,
|
||||||
|
// The tool's "type" column is a case-insensitive substring of the
|
||||||
|
// event name; the web UI's exact/prefix Event filter does not fit.
|
||||||
|
EventContains: args.Type,
|
||||||
|
}
|
||||||
|
q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit)
|
||||||
|
q.Offset = auditquery.ClampOffset(args.Offset)
|
||||||
|
|
||||||
|
res, err := auditquery.Scan(s.cfg.AuditPath, q)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errf(CodeInternal, "failed to read audit log: %v", err)
|
||||||
|
}
|
||||||
|
entries := make([]map[string]any, 0, len(res.Events))
|
||||||
|
for _, rec := range res.Events {
|
||||||
|
entries = append(entries, map[string]any{
|
||||||
|
"type": auditquery.StringField(rec, "event"),
|
||||||
|
"time": auditquery.StringField(rec, "time"),
|
||||||
|
"msg": auditMessage(rec),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Scan caps Offset at auditquery.MaxOffset, so a page that reaches that
|
||||||
|
// point must not advertise a next page: the follow-up offset would be
|
||||||
|
// clamped back and return the same records forever.
|
||||||
|
reached := q.Offset + len(entries)
|
||||||
|
structured := map[string]any{
|
||||||
|
"entries": entries,
|
||||||
|
"total": res.Total,
|
||||||
|
"totalAll": res.TotalAll,
|
||||||
|
"limit": q.Limit,
|
||||||
|
"offset": q.Offset,
|
||||||
|
"hasMore": reached < res.Total && reached < auditquery.MaxOffset,
|
||||||
|
}
|
||||||
|
text := pageSummary(res.Total, q.Limit, q.Offset, "条日志")
|
||||||
|
if res.Total != res.TotalAll {
|
||||||
|
text += fmt.Sprintf("过滤前共 %d 条。", res.TotalAll)
|
||||||
|
}
|
||||||
|
if res.Truncated {
|
||||||
|
text += "(审计文件较大,仅扫描最近 32 MB。)"
|
||||||
|
}
|
||||||
|
return newToolResult(text, structured), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// auditMessage renders the non-envelope fields as compact JSON. The web audit
|
||||||
|
// page shows the raw record; the MCP entry has dedicated type/time columns, so
|
||||||
|
// repeating them inside msg would only add noise.
|
||||||
|
func auditMessage(rec map[string]any) string {
|
||||||
|
rest := make(map[string]any, len(rec))
|
||||||
|
for k, v := range rec {
|
||||||
|
switch k {
|
||||||
|
case "audit", "level", "time", "event":
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rest[k] = v
|
||||||
|
}
|
||||||
|
if len(rest) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
b, err := json.Marshal(rest)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- shared helpers -------------------------------------------------------
|
||||||
|
|
||||||
|
func clampPageLimit(n int) int {
|
||||||
|
if n <= 0 {
|
||||||
|
return listDefaultLimit
|
||||||
|
}
|
||||||
|
if n > listMaxLimit {
|
||||||
|
return listMaxLimit
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageSummary mirrors the Win32 server's summary line:
|
||||||
|
// 「共 N 台主机,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
|
||||||
|
func pageSummary(total, limit, offset int, unit string) string {
|
||||||
|
out := fmt.Sprintf("共 %d %s", total, unit)
|
||||||
|
if total == 0 {
|
||||||
|
return out + "。"
|
||||||
|
}
|
||||||
|
begin := min(offset, total)
|
||||||
|
if begin >= total {
|
||||||
|
return out + ",offset 超出范围,本次返回 0 条。"
|
||||||
|
}
|
||||||
|
end := min(begin+limit, total)
|
||||||
|
out += fmt.Sprintf(",本次返回第 %d-%d 条", begin+1, end)
|
||||||
|
if end < total {
|
||||||
|
out += "(还有更多,可用 offset 继续取)"
|
||||||
|
}
|
||||||
|
return out + "。"
|
||||||
|
}
|
||||||
|
|
||||||
|
// isDecimalID reports whether id is a non-empty decimal string. Host IDs are
|
||||||
|
// uint64 rendered in decimal; anything else is a caller mistake.
|
||||||
|
func isDecimalID(id string) bool {
|
||||||
|
if id == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range id {
|
||||||
|
if r < '0' || r > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// monitorCount parses the "N:W*H" screen string the client reports. 0 means
|
||||||
|
// "not reported / not in that form".
|
||||||
|
func monitorCount(screen string) int {
|
||||||
|
i := strings.IndexByte(screen, ':')
|
||||||
|
if i <= 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(strings.TrimSpace(screen[:i]))
|
||||||
|
if err != nil || n < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
@@ -0,0 +1,679 @@
|
|||||||
|
package mcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
|
)
|
||||||
|
|
||||||
|
// localFixture is the shared setup for the four local read tools: three online
|
||||||
|
// hosts (two Windows in one group, one Linux), two offline history entries, and
|
||||||
|
// a history store that is subscribed to the hub.
|
||||||
|
type localFixture struct {
|
||||||
|
srv *Server
|
||||||
|
hub *hub.Hub
|
||||||
|
hist *devicehistory.Store
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLocalFixture(t *testing.T) *localFixture {
|
||||||
|
t.Helper()
|
||||||
|
h := hub.New()
|
||||||
|
hist, err := devicehistory.Open(filepath.Join(t.TempDir(), "devices.json"), 100, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open history: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = hist.Close() })
|
||||||
|
h.Subscribe(hist)
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
register := func(d hub.Device, clientType string) {
|
||||||
|
h.Register(&d, &connection.Context{
|
||||||
|
RemoteAddr: d.PeerIP + ":40000",
|
||||||
|
Info: connection.ClientInfo{ClientType: clientType},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
register(hub.Device{
|
||||||
|
ID: "1001", Name: "ALPHA", Version: "1.2.3", Capability: "0005",
|
||||||
|
OS: "Windows 10", PublicIP: "10.0.0.1", PeerIP: "192.168.1.1",
|
||||||
|
Resolution: "1:1920*1080", ConnectedAt: now.Add(-3 * time.Minute),
|
||||||
|
}, "EXE")
|
||||||
|
register(hub.Device{
|
||||||
|
ID: "1002", Name: "BETA", Group: "Office", Version: "1.2.3", Capability: "0005",
|
||||||
|
OS: "Windows 11", PeerIP: "192.168.1.2",
|
||||||
|
Resolution: "2:3840*2160", ConnectedAt: now.Add(-2 * time.Minute),
|
||||||
|
}, "EXE")
|
||||||
|
register(hub.Device{
|
||||||
|
ID: "1003", Name: "GAMMA", Group: "Office", Version: "1.1.0",
|
||||||
|
OS: "Ubuntu 24.04", PublicIP: "10.1.0.3", PeerIP: "192.168.1.3",
|
||||||
|
Resolution: "1:2560*1440", ConnectedAt: now.Add(-time.Minute),
|
||||||
|
}, "LNX")
|
||||||
|
h.UpdateLive("1001", 42, "Notepad")
|
||||||
|
h.UpdateLive("1003", 120, "")
|
||||||
|
|
||||||
|
// Two devices that logged in and then left, so the history store has
|
||||||
|
// offline entries to merge into listings.
|
||||||
|
register(hub.Device{
|
||||||
|
ID: "2001", Name: "OLDWIN", Group: "Legacy", Version: "0.9.0", Capability: "0002",
|
||||||
|
OS: "Windows 7", PublicIP: "10.9.0.1", PeerIP: "192.168.9.1",
|
||||||
|
Resolution: "1:1280*1024", ConnectedAt: now.Add(-10 * time.Minute),
|
||||||
|
}, "EXE")
|
||||||
|
register(hub.Device{
|
||||||
|
ID: "2002", Name: "OLDMAC", Version: "0.8.0",
|
||||||
|
OS: "macOS 14", PublicIP: "10.9.0.2", PeerIP: "192.168.9.2",
|
||||||
|
Resolution: "1:1440*900", ConnectedAt: now.Add(-9 * time.Minute),
|
||||||
|
}, "MAC")
|
||||||
|
h.Unregister("2001")
|
||||||
|
h.Unregister("2002")
|
||||||
|
|
||||||
|
srv := New(Config{
|
||||||
|
Token: "test-token",
|
||||||
|
Hub: h,
|
||||||
|
History: hist,
|
||||||
|
Version: "v9.9.9",
|
||||||
|
StartedAt: time.Now().Add(-90 * time.Second),
|
||||||
|
Port: 6544,
|
||||||
|
Bind: "0.0.0.0",
|
||||||
|
})
|
||||||
|
return &localFixture{srv: srv, hub: h, hist: hist}
|
||||||
|
}
|
||||||
|
|
||||||
|
// callLocal drives one tools/call through the same gate the HTTP path uses and
|
||||||
|
// returns the decoded structuredContent plus the text item.
|
||||||
|
func callLocal(t *testing.T, s *Server, name, args string) (string, map[string]any, *rpcError) {
|
||||||
|
t.Helper()
|
||||||
|
params := fmt.Sprintf(`{"name":%q,"arguments":%s}`, name, args)
|
||||||
|
res, rerr := s.callTool(context.Background(), json.RawMessage(params))
|
||||||
|
if rerr != nil {
|
||||||
|
return "", nil, rerr
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(res)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal tool result: %v", err)
|
||||||
|
}
|
||||||
|
var env struct {
|
||||||
|
Content []struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
} `json:"content"`
|
||||||
|
StructuredContent map[string]any `json:"structuredContent"`
|
||||||
|
IsError bool `json:"isError"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &env); err != nil {
|
||||||
|
t.Fatalf("decode tool result: %v", err)
|
||||||
|
}
|
||||||
|
if env.IsError {
|
||||||
|
t.Fatalf("isError = true on success path: %s", raw)
|
||||||
|
}
|
||||||
|
if len(env.Content) != 1 || env.Content[0].Type != "text" {
|
||||||
|
t.Fatalf("content = %+v, want one text item", env.Content)
|
||||||
|
}
|
||||||
|
return env.Content[0].Text, env.StructuredContent, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustCallLocal(t *testing.T, s *Server, name, args string) (string, map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
text, sc, rerr := callLocal(t, s, name, args)
|
||||||
|
if rerr != nil {
|
||||||
|
t.Fatalf("%s returned error %d: %s", name, rerr.Code, rerr.Message)
|
||||||
|
}
|
||||||
|
return text, sc
|
||||||
|
}
|
||||||
|
|
||||||
|
func intField(t *testing.T, m map[string]any, key string) int {
|
||||||
|
t.Helper()
|
||||||
|
v, ok := m[key]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("missing %q in %v", key, m)
|
||||||
|
}
|
||||||
|
f, ok := v.(float64)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%q = %v (%T), want number", key, v, v)
|
||||||
|
}
|
||||||
|
return int(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolField(t *testing.T, m map[string]any, key string) bool {
|
||||||
|
t.Helper()
|
||||||
|
v, ok := m[key]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("missing %q in %v", key, m)
|
||||||
|
}
|
||||||
|
b, ok := v.(bool)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%q = %v (%T), want bool", key, v, v)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func strField(t *testing.T, m map[string]any, key string) string {
|
||||||
|
t.Helper()
|
||||||
|
v, ok := m[key]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("missing %q in %v", key, m)
|
||||||
|
}
|
||||||
|
s, ok := v.(string)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%q = %v (%T), want string", key, v, v)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func hostList(t *testing.T, sc map[string]any) []map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
raw, ok := sc["hosts"].([]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("hosts = %v (%T), want array", sc["hosts"], sc["hosts"])
|
||||||
|
}
|
||||||
|
out := make([]map[string]any, 0, len(raw))
|
||||||
|
for _, item := range raw {
|
||||||
|
m, ok := item.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("host entry = %v (%T), want object", item, item)
|
||||||
|
}
|
||||||
|
out = append(out, m)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func hostIDs(hosts []map[string]any) []string {
|
||||||
|
ids := make([]string, 0, len(hosts))
|
||||||
|
for _, h := range hosts {
|
||||||
|
ids = append(ids, h["id"].(string))
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
func wantIDs(t *testing.T, hosts []map[string]any, want ...string) {
|
||||||
|
t.Helper()
|
||||||
|
got := hostIDs(hosts)
|
||||||
|
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||||
|
t.Fatalf("ids = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
|
||||||
|
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
|
||||||
|
hosts := hostList(t, sc)
|
||||||
|
wantIDs(t, hosts, "1001", "1002", "1003")
|
||||||
|
if got := intField(t, sc, "total"); got != 3 {
|
||||||
|
t.Fatalf("total = %d, want 3", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 3 {
|
||||||
|
t.Fatalf("totalAll = %d, want 3", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "limit"); got != 100 {
|
||||||
|
t.Fatalf("limit = %d, want default 100", got)
|
||||||
|
}
|
||||||
|
if boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = true for a full 3-host page")
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, "共 3 台主机") {
|
||||||
|
t.Fatalf("text = %q, want host count", text)
|
||||||
|
}
|
||||||
|
|
||||||
|
alpha := hosts[0]
|
||||||
|
if got := strField(t, alpha, "name"); got != "ALPHA" {
|
||||||
|
t.Fatalf("name = %q", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, alpha, "group"); got != "default" {
|
||||||
|
t.Fatalf("group = %q, want normalized default", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, alpha, "clientType"); got != "EXE" {
|
||||||
|
t.Fatalf("clientType = %q", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, alpha, "rtt"); got != "42" {
|
||||||
|
t.Fatalf("rtt = %q, want decimal string", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, alpha, "activeWindow"); got != "Notepad" {
|
||||||
|
t.Fatalf("activeWindow = %q", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, alpha, "ip"); got != "10.0.0.1" {
|
||||||
|
t.Fatalf("ip = %q, want client-reported public IP", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, alpha, "screen"); got != "1:1920*1080" {
|
||||||
|
t.Fatalf("screen = %q", got)
|
||||||
|
}
|
||||||
|
if _, ok := alpha["last_seen"]; ok {
|
||||||
|
t.Fatal("online host carries last_seen")
|
||||||
|
}
|
||||||
|
for _, absent := range []string{"remark", "authStatus", "tls"} {
|
||||||
|
if _, ok := alpha[absent]; ok {
|
||||||
|
t.Fatalf("%s present but the Go server has no such data", absent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// include_offline merges history behind the online hosts.
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"include_offline":true}`)
|
||||||
|
hosts = hostList(t, sc)
|
||||||
|
wantIDs(t, hosts, "1001", "1002", "1003", "2001", "2002")
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 5 {
|
||||||
|
t.Fatalf("totalAll = %d, want 5", got)
|
||||||
|
}
|
||||||
|
for _, h := range hosts[:3] {
|
||||||
|
if !boolField(t, h, "online") {
|
||||||
|
t.Fatalf("%s should be online", h["id"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, h := range hosts[3:] {
|
||||||
|
if boolField(t, h, "online") {
|
||||||
|
t.Fatalf("%s should be offline", h["id"])
|
||||||
|
}
|
||||||
|
if h["last_seen"] == "" || h["last_seen"] == nil {
|
||||||
|
t.Fatalf("%s missing last_seen", h["id"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// online=false lists offline only.
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false}`)
|
||||||
|
hosts = hostList(t, sc)
|
||||||
|
wantIDs(t, hosts, "2001", "2002")
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 2 {
|
||||||
|
t.Fatalf("totalAll = %d, want 2 offline hosts", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListHostsFilters(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
args string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"name substring", `{"name":"beta"}`, []string{"1002"}},
|
||||||
|
{"group substring", `{"group":"office"}`, []string{"1002", "1003"}},
|
||||||
|
{"os substring case-insensitive", `{"os":"windows"}`, []string{"1001", "1002"}},
|
||||||
|
{"client type", `{"client_type":"lnx"}`, []string{"1003"}},
|
||||||
|
{"public ip substring", `{"ip":"10.1.0"}`, []string{"1003"}},
|
||||||
|
{"peer ip fallback", `{"ip":"192.168.1.2"}`, []string{"1002"}},
|
||||||
|
{"query matches name", `{"query":"gamma"}`, []string{"1003"}},
|
||||||
|
{"query matches ip", `{"query":"10.0.0.1"}`, []string{"1001"}},
|
||||||
|
{"filters are ANDed", `{"group":"office","os":"ubuntu"}`, []string{"1003"}},
|
||||||
|
{"no match", `{"name":"zzz"}`, nil},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
text, sc := mustCallLocal(t, f.srv, "list_hosts", tc.args)
|
||||||
|
hosts := hostList(t, sc)
|
||||||
|
wantIDs(t, hosts, tc.want...)
|
||||||
|
if got := intField(t, sc, "total"); got != len(tc.want) {
|
||||||
|
t.Fatalf("total = %d, want %d (text %q)", got, len(tc.want), text)
|
||||||
|
}
|
||||||
|
// totalAll stays the unfiltered pool size.
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 3 {
|
||||||
|
t.Fatalf("totalAll = %d, want 3", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// An empty result must be a JSON array, never null.
|
||||||
|
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"name":"zzz"}`)
|
||||||
|
raw, err := json.Marshal(sc)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(raw), `"hosts":[]`) {
|
||||||
|
t.Fatalf("hosts not an empty array: %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
// client_type cannot match an offline record: history keeps no client type.
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false,"client_type":"EXE"}`)
|
||||||
|
if hosts := hostList(t, sc); len(hosts) != 0 {
|
||||||
|
t.Fatalf("offline client_type filter matched %v, want none", hostIDs(hosts))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListHostsPaging(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"limit":2}`)
|
||||||
|
hosts := hostList(t, sc)
|
||||||
|
wantIDs(t, hosts, "1001", "1002")
|
||||||
|
if got := intField(t, sc, "total"); got != 3 {
|
||||||
|
t.Fatalf("total = %d, want 3", got)
|
||||||
|
}
|
||||||
|
if !boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = false, want true")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":2,"offset":2}`)
|
||||||
|
hosts = hostList(t, sc)
|
||||||
|
wantIDs(t, hosts, "1003")
|
||||||
|
if boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = true on the last page")
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "offset"); got != 2 {
|
||||||
|
t.Fatalf("offset = %d, want 2", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{"offset":99}`)
|
||||||
|
if hosts := hostList(t, sc); len(hosts) != 0 {
|
||||||
|
t.Fatalf("offset past end returned %v", hostIDs(hosts))
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, "offset 超出范围") {
|
||||||
|
t.Fatalf("text = %q, want out-of-range note", text)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":5000}`)
|
||||||
|
if got := intField(t, sc, "limit"); got != listMaxLimit {
|
||||||
|
t.Fatalf("limit = %d, want clamped to %d", got, listMaxLimit)
|
||||||
|
}
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":-5}`)
|
||||||
|
if got := intField(t, sc, "limit"); got != listDefaultLimit {
|
||||||
|
t.Fatalf("limit = %d, want default %d", got, listDefaultLimit)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Malformed arguments are a caller error, not an empty list.
|
||||||
|
if _, _, rerr := callLocal(t, f.srv, "list_hosts", `{"limit":"many"}`); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||||
|
t.Fatalf("malformed limit error = %+v, want -32602", rerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetHostDetailOnlineAndOffline(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1001"}`)
|
||||||
|
host, ok := sc["host"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("host = %v", sc["host"])
|
||||||
|
}
|
||||||
|
if !boolField(t, host, "online") {
|
||||||
|
t.Fatal("1001 should be online")
|
||||||
|
}
|
||||||
|
caps, ok := host["capabilities"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("capabilities = %v", host["capabilities"])
|
||||||
|
}
|
||||||
|
if !boolField(t, caps, "screenPreview") || !boolField(t, caps, "fileTransferV2") {
|
||||||
|
t.Fatalf("caps = %v, want preview+V2 from 0x0005", caps)
|
||||||
|
}
|
||||||
|
if boolField(t, caps, "screenRegion") {
|
||||||
|
t.Fatalf("caps = %v, screenRegion set without 0x0200", caps)
|
||||||
|
}
|
||||||
|
if !boolField(t, caps, "registry") {
|
||||||
|
t.Fatalf("caps = %v, Windows client must have registry", caps)
|
||||||
|
}
|
||||||
|
if !boolField(t, caps, "remoteControl") {
|
||||||
|
t.Fatalf("caps = %v, single-monitor Windows must allow remote control", caps)
|
||||||
|
}
|
||||||
|
if got := strField(t, caps, "platform"); got != "EXE" {
|
||||||
|
t.Fatalf("platform = %q", got)
|
||||||
|
}
|
||||||
|
if _, ok := caps["v2"]; ok {
|
||||||
|
t.Fatal("v2 must not be reported: every platform sets it")
|
||||||
|
}
|
||||||
|
|
||||||
|
// A multi-monitor Windows client without whole-desktop capture is not
|
||||||
|
// remotely controllable (coordinate spaces would not line up).
|
||||||
|
f.hub.Register(&hub.Device{
|
||||||
|
ID: "1004", Name: "DUAL", Capability: "0005",
|
||||||
|
OS: "Windows 11", PublicIP: "10.0.0.4", PeerIP: "192.168.1.4",
|
||||||
|
Resolution: "2:3840*2160", ConnectedAt: time.Now(),
|
||||||
|
}, &connection.Context{RemoteAddr: "192.168.1.4:40000",
|
||||||
|
Info: connection.ClientInfo{ClientType: "EXE"}})
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1004"}`)
|
||||||
|
caps = sc["host"].(map[string]any)["capabilities"].(map[string]any)
|
||||||
|
if boolField(t, caps, "remoteControl") {
|
||||||
|
t.Fatalf("caps = %v, dual-monitor without VIRTUAL_DESKTOP must not allow remote control", caps)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Offline detail comes from history: no capabilities (the device is gone),
|
||||||
|
// but the last-known fields are intact.
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "get_host_detail", `{"id":"2001"}`)
|
||||||
|
host = sc["host"].(map[string]any)
|
||||||
|
if boolField(t, host, "online") {
|
||||||
|
t.Fatal("2001 should be offline")
|
||||||
|
}
|
||||||
|
if got := strField(t, host, "version"); got != "0.9.0" {
|
||||||
|
t.Fatalf("version = %q", got)
|
||||||
|
}
|
||||||
|
if _, ok := host["capabilities"]; ok {
|
||||||
|
t.Fatal("offline host must not report capabilities")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{"id":"9999"}`); rerr == nil || rerr.Code != CodeOffline {
|
||||||
|
t.Fatalf("unknown host error = %+v, want -32002", rerr)
|
||||||
|
}
|
||||||
|
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{"id":"12ab"}`); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||||
|
t.Fatalf("non-decimal id error = %+v, want -32602", rerr)
|
||||||
|
}
|
||||||
|
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{}`); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||||
|
t.Fatalf("missing id error = %+v, want -32602", rerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetHostDetailBatch(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","9999","2001"]}`)
|
||||||
|
if got := strField(t, sc, "tool"); got != "get_host_detail" {
|
||||||
|
t.Fatalf("tool = %q", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "total"); got != 3 {
|
||||||
|
t.Fatalf("total = %d, want 3", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "succeeded"); got != 2 {
|
||||||
|
t.Fatalf("succeeded = %d, want 2", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "failed"); got != 1 {
|
||||||
|
t.Fatalf("failed = %d, want 1", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "skipped"); got != 0 {
|
||||||
|
t.Fatalf("skipped = %d, want 0", got)
|
||||||
|
}
|
||||||
|
results, ok := sc["results"].([]any)
|
||||||
|
if !ok || len(results) != 3 {
|
||||||
|
t.Fatalf("results = %v", sc["results"])
|
||||||
|
}
|
||||||
|
first := results[0].(map[string]any)
|
||||||
|
if !boolField(t, first, "ok") {
|
||||||
|
t.Fatal("first result should be ok")
|
||||||
|
}
|
||||||
|
data := first["data"].(map[string]any)
|
||||||
|
if id := strField(t, data["host"].(map[string]any), "id"); id != "1001" {
|
||||||
|
t.Fatalf("first host id = %q", id)
|
||||||
|
}
|
||||||
|
second := results[1].(map[string]any)
|
||||||
|
if boolField(t, second, "ok") {
|
||||||
|
t.Fatal("second result should fail")
|
||||||
|
}
|
||||||
|
errObj := second["error"].(map[string]any)
|
||||||
|
if got := intField(t, errObj, "code"); got != CodeOffline {
|
||||||
|
t.Fatalf("per-entry code = %d, want %d", got, CodeOffline)
|
||||||
|
}
|
||||||
|
third := results[2].(map[string]any)
|
||||||
|
if !boolField(t, third, "ok") {
|
||||||
|
t.Fatal("offline history entry should succeed in a batch")
|
||||||
|
}
|
||||||
|
|
||||||
|
ids := make([]string, batchMaxIDs+1)
|
||||||
|
for i := range ids {
|
||||||
|
ids[i] = "1001"
|
||||||
|
}
|
||||||
|
payload, _ := json.Marshal(map[string]any{"ids": ids})
|
||||||
|
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", string(payload)); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||||
|
t.Fatalf("oversized batch error = %+v, want -32602", rerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetServerStatus(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, f.srv, "get_server_status", `{}`)
|
||||||
|
if got := strField(t, sc, "version"); got != "v9.9.9" {
|
||||||
|
t.Fatalf("version = %q", got)
|
||||||
|
}
|
||||||
|
// StartedAt is 90s in the past; the exact value depends on test runtime.
|
||||||
|
if got := intField(t, sc, "uptime_sec"); got < 90 {
|
||||||
|
t.Fatalf("uptime_sec = %d, want >= 90", got)
|
||||||
|
}
|
||||||
|
hosts, ok := sc["hosts"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("hosts = %v", sc["hosts"])
|
||||||
|
}
|
||||||
|
if got := intField(t, hosts, "online"); got != 3 {
|
||||||
|
t.Fatalf("online = %d, want 3", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, hosts, "offline"); got != 2 {
|
||||||
|
t.Fatalf("offline = %d, want 2", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "port"); got != 6544 {
|
||||||
|
t.Fatalf("port = %d", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, sc, "bind"); got != "0.0.0.0" {
|
||||||
|
t.Fatalf("bind = %q", got)
|
||||||
|
}
|
||||||
|
if _, ok := sc["sessions"]; ok {
|
||||||
|
t.Fatal("sessions reported before the MCP session table exists")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A build without link-time version injection must not invent one: the status
|
||||||
|
// tool reports the empty string, and only initialize substitutes "dev".
|
||||||
|
func TestUnversionedBuild(t *testing.T) {
|
||||||
|
s := New(Config{Token: "test-token"})
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, s, "get_server_status", `{}`)
|
||||||
|
if got, ok := sc["version"]; !ok || got != "" {
|
||||||
|
t.Fatalf("status version = %#v, want empty string", got)
|
||||||
|
}
|
||||||
|
if got := s.initializeResult().ServerInfo.Version; got != "dev" {
|
||||||
|
t.Fatalf("initialize version = %q, want dev", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAuditFile(t *testing.T, lines ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(t.TempDir(), "audit.log")
|
||||||
|
body := strings.Join(lines, "\n") + "\n"
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatalf("write audit file: %v", err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetAuditLog(t *testing.T) {
|
||||||
|
path := writeAuditFile(t,
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"web.login.success","actor":"admin","ip":"1.2.3.4"}`,
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:01:00Z","level":"info","event":"web.login.failure","actor":"bob","ip":"5.6.7.8"}`,
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:02:00Z","level":"warn","event":"authz.denied","actor":"admin","ip":"1.2.3.4","detail":"readonly"}`,
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:03:00Z","level":"info","event":"device.online","device_id":"1001"}`,
|
||||||
|
)
|
||||||
|
s := New(Config{Token: "test-token", AuditPath: path})
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
|
||||||
|
entries, ok := sc["entries"].([]any)
|
||||||
|
if !ok || len(entries) != 4 {
|
||||||
|
t.Fatalf("entries = %v, want 4", sc["entries"])
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "total"); got != 4 {
|
||||||
|
t.Fatalf("total = %d, want 4", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 4 {
|
||||||
|
t.Fatalf("totalAll = %d, want 4", got)
|
||||||
|
}
|
||||||
|
if boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = true for a complete page")
|
||||||
|
}
|
||||||
|
newest := entries[0].(map[string]any)
|
||||||
|
if got := strField(t, newest, "type"); got != "device.online" {
|
||||||
|
t.Fatalf("newest type = %q, want newest first", got)
|
||||||
|
}
|
||||||
|
if got := strField(t, newest, "time"); got != "2026-11-12T10:03:00Z" {
|
||||||
|
t.Fatalf("newest time = %q", got)
|
||||||
|
}
|
||||||
|
msg := strField(t, newest, "msg")
|
||||||
|
if !strings.Contains(msg, `"device_id":"1001"`) {
|
||||||
|
t.Fatalf("msg = %q, want remaining fields", msg)
|
||||||
|
}
|
||||||
|
for _, envelope := range []string{`"audit"`, `"event"`, `"level"`, `"time"`} {
|
||||||
|
if strings.Contains(msg, envelope) {
|
||||||
|
t.Fatalf("msg repeats envelope key %s: %s", envelope, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// type is a case-insensitive substring of the event name.
|
||||||
|
_, sc = mustCallLocal(t, s, "get_audit_log", `{"type":"LOGIN"}`)
|
||||||
|
if got := intField(t, sc, "total"); got != 2 {
|
||||||
|
t.Fatalf("login total = %d, want 2", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 4 {
|
||||||
|
t.Fatalf("login totalAll = %d, want unfiltered 4", got)
|
||||||
|
}
|
||||||
|
_, sc = mustCallLocal(t, s, "get_audit_log", `{"type":"login","keyword":"1.2.3.4"}`)
|
||||||
|
if got := intField(t, sc, "total"); got != 1 {
|
||||||
|
t.Fatalf("type+keyword total = %d, want 1", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paging: limit 2 → hasMore; the tail page stops there.
|
||||||
|
_, sc = mustCallLocal(t, s, "get_audit_log", `{"limit":2}`)
|
||||||
|
if got := len(sc["entries"].([]any)); got != 2 {
|
||||||
|
t.Fatalf("entries = %d, want 2", got)
|
||||||
|
}
|
||||||
|
if !boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = false with 2 of 4")
|
||||||
|
}
|
||||||
|
_, sc = mustCallLocal(t, s, "get_audit_log", `{"limit":2,"offset":3}`)
|
||||||
|
if got := len(sc["entries"].([]any)); got != 1 {
|
||||||
|
t.Fatalf("tail entries = %d, want 1", got)
|
||||||
|
}
|
||||||
|
if boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = true on the tail page")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty result is an array, and the file is scanned only up to its size.
|
||||||
|
_, sc = mustCallLocal(t, s, "get_audit_log", `{"keyword":"no-such-thing"}`)
|
||||||
|
raw, _ := json.Marshal(sc)
|
||||||
|
if !strings.Contains(string(raw), `"entries":[]`) {
|
||||||
|
t.Fatalf("entries not an empty array: %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Missing file: an empty log, not an error.
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
f.srv.cfg.AuditPath = filepath.Join(t.TempDir(), "missing.log")
|
||||||
|
if _, sc = mustCallLocal(t, f.srv, "get_audit_log", `{}`); intField(t, sc, "total") != 0 {
|
||||||
|
t.Fatalf("missing file total = %d, want 0", intField(t, sc, "total"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disabled audit file (YAMA_AUDIT_LOG=off) is a configuration error.
|
||||||
|
off := New(Config{Token: "test-token"})
|
||||||
|
if _, _, rerr := callLocal(t, off, "get_audit_log", `{}`); rerr == nil || rerr.Code != CodeInternal {
|
||||||
|
t.Fatalf("disabled audit error = %+v, want -32000", rerr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Offset is clamped at auditquery.MaxOffset. A page that ends exactly
|
||||||
|
// there must not advertise a next page: the follow-up offset would be
|
||||||
|
// clamped back and return the same records forever.
|
||||||
|
var big strings.Builder
|
||||||
|
for i := range auditquery.MaxOffset + 2000 {
|
||||||
|
fmt.Fprintf(&big, `{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"device.online","n":%d}`+"\n", i)
|
||||||
|
}
|
||||||
|
bigPath := filepath.Join(t.TempDir(), "audit.log")
|
||||||
|
if err := os.WriteFile(bigPath, []byte(big.String()), 0o600); err != nil {
|
||||||
|
t.Fatalf("write big audit file: %v", err)
|
||||||
|
}
|
||||||
|
bigSrv := New(Config{Token: "test-token", AuditPath: bigPath})
|
||||||
|
_, sc = mustCallLocal(t, bigSrv, "get_audit_log", `{"limit":500}`)
|
||||||
|
if !boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = false on the first page of a large log")
|
||||||
|
}
|
||||||
|
_, sc = mustCallLocal(t, bigSrv, "get_audit_log", `{"limit":500,"offset":9500}`)
|
||||||
|
if got := len(sc["entries"].([]any)); got != 500 {
|
||||||
|
t.Fatalf("entries at cap = %d, want 500", got)
|
||||||
|
}
|
||||||
|
if boolField(t, sc, "hasMore") {
|
||||||
|
t.Fatal("hasMore = true at the MaxOffset cap, paging would loop")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,6 +69,13 @@ const (
|
|||||||
ClientCapV2 uint32 = 0x0001 // CLIENT_CAP_V2 — V2 file transfer
|
ClientCapV2 uint32 = 0x0001 // CLIENT_CAP_V2 — V2 file transfer
|
||||||
ClientCapUTF8 uint32 = 0x0002 // CLIENT_CAP_UTF8 — UTF-8 protocol strings (activeWindow, key-log titles, ...)
|
ClientCapUTF8 uint32 = 0x0002 // CLIENT_CAP_UTF8 — UTF-8 protocol strings (activeWindow, key-log titles, ...)
|
||||||
ClientCapScreenPreview uint32 = 0x0004 // CLIENT_CAP_SCREEN_PREVIEW
|
ClientCapScreenPreview uint32 = 0x0004 // CLIENT_CAP_SCREEN_PREVIEW
|
||||||
|
ClientCapC2CPaths uint32 = 0x0008 // CLIENT_CAP_C2C_PATHS — path-list driven host-to-host transfer
|
||||||
|
// Bits 0x0010 (C2C recv ack), 0x0020 (protocol switch) and 0x0040
|
||||||
|
// (embedded anchor) are not consumed by the Go server yet. They are simply
|
||||||
|
// skipped by the constants below.
|
||||||
|
ClientCapVirtualDesktop uint32 = 0x0080 // CLIENT_CAP_VIRTUAL_DESKTOP — whole virtual desktop capture
|
||||||
|
ClientCapWindowInfo uint32 = 0x0100 // CLIENT_CAP_WINDOW_INFO — window enumeration / rects
|
||||||
|
ClientCapScreenRegion uint32 = 0x0200 // CLIENT_CAP_SCREEN_REGION — region/window/monitor capture
|
||||||
)
|
)
|
||||||
|
|
||||||
// SupportsCap returns true when the client's reported capability hex string
|
// SupportsCap returns true when the client's reported capability hex string
|
||||||
|
|||||||
+13
-250
@@ -1,57 +1,21 @@
|
|||||||
package web
|
package web
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"os"
|
|
||||||
"strings"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Audit-log query support for the admin-only "Audit Log" page.
|
// Audit-log query support for the admin-only "Audit Log" page.
|
||||||
//
|
//
|
||||||
// The server reads its own JSON-lines audit file (logs/audit.log) back to the
|
// The scanner itself (file tail, filters, paging) lives in package
|
||||||
// browser. Records are already redacted at write time (see logger.AuditAt), so
|
// auditquery so the MCP get_audit_log tool can share it; this file keeps only
|
||||||
// returning raw lines is safe as long as we never widen what is written.
|
// the WebSocket command handler and the reply shaping specific to the UI.
|
||||||
//
|
|
||||||
// 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 the UI is meant for recent-window triage ("what happened just now").
|
|
||||||
const (
|
|
||||||
auditQueryDefaultLimit = 100
|
|
||||||
auditQueryMaxLimit = 500
|
|
||||||
auditQueryMaxOffset = 10000
|
|
||||||
|
|
||||||
// auditQueryScanBudget bounds how much of the audit file a single query
|
// auditQueryMaxLimit caps the page size of the audit page. It is tighter than
|
||||||
// reads. The tail is read when the file is larger, so the newest records
|
// auditquery.MaxLimit (the protocol-wide cap the MCP tool uses) because the
|
||||||
// (what operators actually triage) are always covered and a multi-GB log
|
// admin table is meant to be paged, not downloaded.
|
||||||
// cannot stall the WS goroutine.
|
const auditQueryMaxLimit = 500
|
||||||
auditQueryScanBudget = 32 << 20 // 32 MB
|
|
||||||
)
|
|
||||||
|
|
||||||
// auditQueryRequest is the JSON body of the `query_audit` command.
|
|
||||||
type auditQueryRequest 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
|
|
||||||
Limit int `json:"limit"`
|
|
||||||
Offset int `json:"offset"` // skip the newest N matching records
|
|
||||||
}
|
|
||||||
|
|
||||||
// auditQueryResult is the internal result of scanning the audit file.
|
|
||||||
type auditQueryResult struct {
|
|
||||||
Events []map[string]any
|
|
||||||
Total int // matching records in the scanned window
|
|
||||||
FileExists bool
|
|
||||||
FileSize int64
|
|
||||||
ScannedBytes int64
|
|
||||||
Truncated bool // the file was larger than auditQueryScanBudget
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleQueryAudit implements the admin-only audit query command. The reply is
|
// handleQueryAudit implements the admin-only audit query command. The reply is
|
||||||
// `{cmd:"audit_result", ok, events, total, ...}`; events are newest-first.
|
// `{cmd:"audit_result", ok, events, total, ...}`; events are newest-first.
|
||||||
@@ -60,13 +24,13 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
|||||||
if !h.requireAdmin(c, raw, replyCmd) {
|
if !h.requireAdmin(c, raw, replyCmd) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var in auditQueryRequest
|
var in auditquery.Query
|
||||||
if err := json.Unmarshal(raw, &in); err != nil {
|
if err := json.Unmarshal(raw, &in); err != nil {
|
||||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Invalid request"}))
|
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Invalid request"}))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
in.Limit = clampAuditLimit(in.Limit)
|
in.Limit = auditquery.ClampLimit(in.Limit, auditQueryMaxLimit)
|
||||||
in.Offset = clampAuditOffset(in.Offset)
|
in.Offset = auditquery.ClampOffset(in.Offset)
|
||||||
|
|
||||||
path := h.log.AuditPath()
|
path := h.log.AuditPath()
|
||||||
if path == "" {
|
if path == "" {
|
||||||
@@ -81,7 +45,7 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
res, err := queryAuditLog(path, in)
|
res, err := auditquery.Scan(path, in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.audit(c, true, auditQuery, map[string]any{
|
h.audit(c, true, auditQuery, map[string]any{
|
||||||
"ok": false,
|
"ok": false,
|
||||||
@@ -125,204 +89,3 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
|||||||
"truncated": res.Truncated,
|
"truncated": res.Truncated,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
func clampAuditLimit(n int) int {
|
|
||||||
if n <= 0 {
|
|
||||||
return auditQueryDefaultLimit
|
|
||||||
}
|
|
||||||
if n > auditQueryMaxLimit {
|
|
||||||
return auditQueryMaxLimit
|
|
||||||
}
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
func clampAuditOffset(n int) int {
|
|
||||||
if n < 0 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
if n > auditQueryMaxOffset {
|
|
||||||
return auditQueryMaxOffset
|
|
||||||
}
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
// queryAuditLog scans path for audit records matching q. The returned events
|
|
||||||
// are the newest limit records after skipping offset, in newest-first order.
|
|
||||||
func queryAuditLog(path string, q auditQueryRequest) (auditQueryResult, error) {
|
|
||||||
res := auditQueryResult{Events: []map[string]any{}}
|
|
||||||
|
|
||||||
f, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
// No audit record has been written yet (lumberjack creates the file
|
|
||||||
// lazily). An empty result is correct, not an error.
|
|
||||||
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() > auditQueryScanBudget {
|
|
||||||
start = info.Size() - auditQueryScanBudget
|
|
||||||
if _, err := f.Seek(start, 0); err != nil {
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
res.Truncated = true
|
|
||||||
}
|
|
||||||
|
|
||||||
from, hasFrom := parseAuditTime(q.From)
|
|
||||||
to, hasTo := parseAuditTime(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 on the page. 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
|
|
||||||
}
|
|
||||||
if !auditRecordMatches(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
|
|
||||||
}
|
|
||||||
|
|
||||||
// auditRecordMatches applies the non-time and time filters to one record.
|
|
||||||
// line is the raw JSON line, used for the keyword substring search.
|
|
||||||
func auditRecordMatches(rec map[string]any, line string, q auditQueryRequest, from time.Time, hasFrom bool, to time.Time, hasTo bool) bool {
|
|
||||||
if q.Event != "" && !auditEventFilterMatches(q.Event, auditStringField(rec, "event")) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if q.Actor != "" && !strings.EqualFold(auditStringField(rec, "actor"), q.Actor) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if q.IP != "" && auditStringField(rec, "ip") != q.IP {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if q.DeviceID != "" && auditStringField(rec, "device_id") != q.DeviceID {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if q.WarnOnly && auditStringField(rec, "level") != "warn" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if q.Keyword != "" && !strings.Contains(strings.ToLower(line), strings.ToLower(q.Keyword)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if hasFrom || hasTo {
|
|
||||||
t, ok := parseAuditTime(auditStringField(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
|
|
||||||
}
|
|
||||||
|
|
||||||
// auditEventFilterMatches supports three forms so the UI stays simple:
|
|
||||||
//
|
|
||||||
// "web.login.failure" exact
|
|
||||||
// "web.*" prefix (trailing "*")
|
|
||||||
// "web." prefix (trailing ".")
|
|
||||||
func auditEventFilterMatches(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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func auditStringField(rec map[string]any, key string) string {
|
|
||||||
s, _ := rec[key].(string)
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseAuditTime 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 parseAuditTime(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
|
|
||||||
}
|
|
||||||
@@ -2,17 +2,20 @@ package web
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/wsauth"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/wsauth"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// The scanner has its own tests in package auditquery; this file covers the
|
||||||
|
// WebSocket command handler and its reply shape.
|
||||||
|
|
||||||
// newAuditTestHubWithoutAuditFile builds a hub whose logger has no dedicated
|
// newAuditTestHubWithoutAuditFile builds a hub whose logger has no dedicated
|
||||||
// audit file, mirroring a server started with YAMA_AUDIT_LOG=off.
|
// audit file, mirroring a server started with YAMA_AUDIT_LOG=off.
|
||||||
func newAuditTestHubWithoutAuditFile(t *testing.T, dir string) (*wsHub, string) {
|
func newAuditTestHubWithoutAuditFile(t *testing.T, dir string) (*wsHub, string) {
|
||||||
@@ -43,189 +46,6 @@ func readQueuedJSON(t *testing.T, c *wsClient) map[string]any {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeAuditFixture writes JSON-lines audit records (oldest first) and returns
|
|
||||||
// the file path. Times are UTC RFC3339 so the tests are timezone-independent.
|
|
||||||
func writeAuditFixture(t *testing.T, records []map[string]any) string {
|
|
||||||
t.Helper()
|
|
||||||
path := filepath.Join(t.TempDir(), "audit.log")
|
|
||||||
var b strings.Builder
|
|
||||||
for _, rec := range records {
|
|
||||||
line, err := json.Marshal(rec)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("marshal fixture: %v", err)
|
|
||||||
}
|
|
||||||
b.Write(line)
|
|
||||||
b.WriteByte('\n')
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
|
|
||||||
t.Fatalf("write fixture: %v", err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
func auditFixtureRecords() []map[string]any {
|
|
||||||
at := func(hhmm string) string {
|
|
||||||
tm, err := time.Parse("2006-01-02T15:04", "2026-10-18T"+hhmm)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
return tm.Format(time.RFC3339)
|
|
||||||
}
|
|
||||||
return []map[string]any{
|
|
||||||
{"level": "info", "time": at("10:00"), "audit": true, "event": "web.login.success", "actor": "admin", "ip": "203.0.113.1"},
|
|
||||||
{"level": "warn", "time": at("10:01"), "audit": true, "event": "web.login.failure", "actor": "alice", "ip": "203.0.113.2", "reason": "invalid_credentials"},
|
|
||||||
{"level": "info", "time": at("10:02"), "audit": true, "event": "remote.screen.start", "actor": "admin", "role": "admin", "ip": "203.0.113.1", "device_id": "dev1"},
|
|
||||||
{"level": "info", "time": at("10:03"), "audit": true, "event": "admin.user.delete", "actor": "admin", "ip": "203.0.113.1", "target": "bob"},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func runAuditQuery(t *testing.T, path string, q auditQueryRequest) auditQueryResult {
|
|
||||||
t.Helper()
|
|
||||||
q.Limit = clampAuditLimit(q.Limit)
|
|
||||||
q.Offset = clampAuditOffset(q.Offset)
|
|
||||||
res, err := queryAuditLog(path, q)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("queryAuditLog: %v", err)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func eventNames(res auditQueryResult) []string {
|
|
||||||
out := make([]string, 0, len(res.Events))
|
|
||||||
for _, e := range res.Events {
|
|
||||||
out = append(out, auditStringField(e, "event"))
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuditQueryNoFilterNewestFirst(t *testing.T) {
|
|
||||||
path := writeAuditFixture(t, auditFixtureRecords())
|
|
||||||
res := runAuditQuery(t, path, auditQueryRequest{Limit: 100})
|
|
||||||
if res.Total != 4 || len(res.Events) != 4 {
|
|
||||||
t.Fatalf("total=%d events=%d, want 4/4", res.Total, len(res.Events))
|
|
||||||
}
|
|
||||||
got := eventNames(res)
|
|
||||||
want := []string{"admin.user.delete", "remote.screen.start", "web.login.failure", "web.login.success"}
|
|
||||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
|
||||||
t.Fatalf("events = %v, want %v", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuditQueryEventFilters(t *testing.T) {
|
|
||||||
path := writeAuditFixture(t, auditFixtureRecords())
|
|
||||||
cases := []struct {
|
|
||||||
filter string
|
|
||||||
want []string
|
|
||||||
}{
|
|
||||||
{"web.", []string{"web.login.failure", "web.login.success"}},
|
|
||||||
{"web.*", []string{"web.login.failure", "web.login.success"}},
|
|
||||||
{"web.login.failure", []string{"web.login.failure"}},
|
|
||||||
{"remote.*", []string{"remote.screen.start"}},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
res := runAuditQuery(t, path, auditQueryRequest{Event: tc.filter, Limit: 100})
|
|
||||||
got := eventNames(res)
|
|
||||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
|
||||||
t.Errorf("filter %q → %v, want %v", tc.filter, got, tc.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuditQueryFieldFilters(t *testing.T) {
|
|
||||||
path := writeAuditFixture(t, auditFixtureRecords())
|
|
||||||
from, _ := time.Parse(time.RFC3339, "2026-10-18T10:01:00Z")
|
|
||||||
to, _ := time.Parse(time.RFC3339, "2026-10-18T10:02:00Z")
|
|
||||||
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
q auditQueryRequest
|
|
||||||
want []string
|
|
||||||
}{
|
|
||||||
{"actor case-insensitive", auditQueryRequest{Actor: "ALICE", Limit: 100}, []string{"web.login.failure"}},
|
|
||||||
{"ip", auditQueryRequest{IP: "203.0.113.2", Limit: 100}, []string{"web.login.failure"}},
|
|
||||||
{"device", auditQueryRequest{DeviceID: "dev1", Limit: 100}, []string{"remote.screen.start"}},
|
|
||||||
{"warn only", auditQueryRequest{WarnOnly: true, Limit: 100}, []string{"web.login.failure"}},
|
|
||||||
{"keyword target", auditQueryRequest{Keyword: "BOB", Limit: 100}, []string{"admin.user.delete"}},
|
|
||||||
{"time range", auditQueryRequest{
|
|
||||||
From: from.Format(time.RFC3339), To: to.Format(time.RFC3339), Limit: 100,
|
|
||||||
}, []string{"remote.screen.start", "web.login.failure"}},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
res := runAuditQuery(t, path, tc.q)
|
|
||||||
got := eventNames(res)
|
|
||||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
|
||||||
t.Errorf("%s → %v, want %v", tc.name, got, tc.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuditQueryOffsetAndLimit(t *testing.T) {
|
|
||||||
path := writeAuditFixture(t, auditFixtureRecords())
|
|
||||||
res := runAuditQuery(t, path, auditQueryRequest{Limit: 2, Offset: 1})
|
|
||||||
if res.Total != 4 {
|
|
||||||
t.Fatalf("total = %d, want 4", res.Total)
|
|
||||||
}
|
|
||||||
got := eventNames(res)
|
|
||||||
want := []string{"remote.screen.start", "web.login.failure"}
|
|
||||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
|
||||||
t.Fatalf("events = %v, want %v", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Offsetting past the end yields no events but keeps the total.
|
|
||||||
res = runAuditQuery(t, path, auditQueryRequest{Limit: 2, Offset: 4})
|
|
||||||
if res.Total != 4 || len(res.Events) != 0 {
|
|
||||||
t.Fatalf("offset past end: total=%d events=%v", res.Total, eventNames(res))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuditQuerySkipsNonAuditAndTornLines(t *testing.T) {
|
|
||||||
path := filepath.Join(t.TempDir(), "audit.log")
|
|
||||||
content := `{"event":"device.online","actor":"x"}
|
|
||||||
not json at all
|
|
||||||
{"level":"info","time":"2026-10-18T10:00:00Z","audit":true,"event":"web.login.success","actor":"admin"}`
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
res := runAuditQuery(t, path, auditQueryRequest{Limit: 100})
|
|
||||||
if res.Total != 1 || len(res.Events) != 1 {
|
|
||||||
t.Fatalf("total=%d events=%v, want the single valid record", res.Total, eventNames(res))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuditQueryMissingFile(t *testing.T) {
|
|
||||||
res := runAuditQuery(t, filepath.Join(t.TempDir(), "does-not-exist.log"), auditQueryRequest{Limit: 10})
|
|
||||||
if res.FileExists {
|
|
||||||
t.Error("FileExists = true for a missing file")
|
|
||||||
}
|
|
||||||
if res.Total != 0 || len(res.Events) != 0 {
|
|
||||||
t.Errorf("total=%d events=%v, want empty", res.Total, eventNames(res))
|
|
||||||
}
|
|
||||||
if res.Events == nil {
|
|
||||||
t.Error("Events is nil; JSON would encode null instead of []")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuditQueryClampsPaging(t *testing.T) {
|
|
||||||
if got := clampAuditLimit(0); got != auditQueryDefaultLimit {
|
|
||||||
t.Errorf("limit(0) = %d, want default %d", got, auditQueryDefaultLimit)
|
|
||||||
}
|
|
||||||
if got := clampAuditLimit(-3); got != auditQueryDefaultLimit {
|
|
||||||
t.Errorf("limit(-3) = %d, want default %d", got, auditQueryDefaultLimit)
|
|
||||||
}
|
|
||||||
if got := clampAuditLimit(9999); got != auditQueryMaxLimit {
|
|
||||||
t.Errorf("limit(9999) = %d, want max %d", got, auditQueryMaxLimit)
|
|
||||||
}
|
|
||||||
if got := clampAuditLimit(50); got != 50 {
|
|
||||||
t.Errorf("limit(50) = %d, want 50", got)
|
|
||||||
}
|
|
||||||
if got := clampAuditOffset(-5); got != 0 {
|
|
||||||
t.Errorf("offset(-5) = %d, want 0", got)
|
|
||||||
}
|
|
||||||
if got := clampAuditOffset(1 << 30); got != auditQueryMaxOffset {
|
|
||||||
t.Errorf("offset(huge) = %d, want max %d", got, auditQueryMaxOffset)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestQueryAuditHandlerAdminOnly(t *testing.T) {
|
func TestQueryAuditHandlerAdminOnly(t *testing.T) {
|
||||||
wh, _, _ := auditTestHub(t)
|
wh, _, _ := auditTestHub(t)
|
||||||
viewer, tok := auditTestClient(wh, "viewer")
|
viewer, tok := auditTestClient(wh, "viewer")
|
||||||
@@ -265,7 +85,7 @@ func TestQueryAuditHandlerReturnsEvents(t *testing.T) {
|
|||||||
var names []string
|
var names []string
|
||||||
for _, e := range events {
|
for _, e := range events {
|
||||||
if m, ok := e.(map[string]any); ok {
|
if m, ok := e.(map[string]any); ok {
|
||||||
names = append(names, auditStringField(m, "event"))
|
names = append(names, auditquery.StringField(m, "event"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
joined := strings.Join(names, ",")
|
joined := strings.Join(names, ",")
|
||||||
|
|||||||
Reference in new issue
Block a user