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
+25
-5
@@ -11,6 +11,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||
)
|
||||
|
||||
@@ -39,6 +41,15 @@ type Config struct {
|
||||
Version string // serverInfo.version
|
||||
StartedAt time.Time // reported by get_server_status
|
||||
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
|
||||
@@ -69,18 +80,21 @@ func New(cfg Config) *Server {
|
||||
if cfg.StartedAt.IsZero() {
|
||||
cfg.StartedAt = time.Now()
|
||||
}
|
||||
if cfg.Version == "" {
|
||||
cfg.Version = "dev"
|
||||
}
|
||||
// Version is left exactly as injected: it may be empty in a build without
|
||||
// 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 {
|
||||
cfg.Log = logger.New(logger.Config{Level: logger.LevelError})
|
||||
}
|
||||
return &Server{
|
||||
s := &Server{
|
||||
cfg: cfg,
|
||||
log: cfg.Log,
|
||||
tools: buildToolSet(toolsJSON),
|
||||
handlers: make(map[string]toolFunc),
|
||||
}
|
||||
s.registerLocalTools()
|
||||
return s
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Differences are stated in instructions, which models read.
|
||||
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{
|
||||
ProtocolVersion: protocolVersion,
|
||||
Capabilities: serverCapabilities{Tools: toolsCapability{ListChanged: false}},
|
||||
ServerInfo: serverInfo{Name: "yama", Version: s.cfg.Version},
|
||||
ServerInfo: serverInfo{Name: "yama", Version: version},
|
||||
Instructions: serverInstructions,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,7 +370,9 @@ func TestToolsCallGates(t *testing.T) {
|
||||
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,
|
||||
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_hosts"}}`,
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user