Files
SimpleRemoter/server/go/web/audit_query_test.go
T
yuanyuanxianganddeepseek-flash 774c0d2545 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
2026-11-12 20:55:18 +01:00

115 lines
3.6 KiB
Go

package web
import (
"encoding/json"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
"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
// audit file, mirroring a server started with YAMA_AUDIT_LOG=off.
func newAuditTestHubWithoutAuditFile(t *testing.T, dir string) (*wsHub, string) {
t.Helper()
lg := logger.New(logger.Config{
Level: logger.LevelInfo,
Console: false,
File: filepath.Join(dir, "server.log"),
})
t.Cleanup(func() { _ = lg.Close() })
wh := newWSHub(wsauth.New(), hub.New(), nil, lg)
t.Cleanup(wh.stop)
return wh, ""
}
func readQueuedJSON(t *testing.T, c *wsClient) map[string]any {
t.Helper()
select {
case m := <-c.send:
var v map[string]any
if err := json.Unmarshal(m.data, &v); err != nil {
t.Fatalf("queued reply is not JSON: %q: %v", m.data, err)
}
return v
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for a queued reply")
return nil
}
}
func TestQueryAuditHandlerAdminOnly(t *testing.T) {
wh, _, _ := auditTestHub(t)
viewer, tok := auditTestClient(wh, "viewer")
raw, _ := json.Marshal(map[string]any{"token": tok})
wh.handleQueryAudit(viewer, raw)
msg := readQueuedJSON(t, viewer)
if msg["cmd"] != "audit_result" || msg["ok"] != false {
t.Fatalf("viewer reply = %+v", msg)
}
if _, ok := msg["events"]; ok {
t.Error("denied viewer got events")
}
}
func TestQueryAuditHandlerReturnsEvents(t *testing.T) {
wh, _, _ := auditTestHub(t)
// Two records written directly through the same logger the hub queries.
wh.log.Audit("web.login.success", map[string]any{"actor": "admin", "ip": "203.0.113.1"})
wh.log.Audit("remote.screen.start", map[string]any{"actor": "admin", "device_id": "dev1"})
admin, tok := auditTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{"token": tok, "limit": 10})
wh.handleQueryAudit(admin, raw)
msg := readQueuedJSON(t, admin)
if msg["cmd"] != "audit_result" || msg["ok"] != true {
t.Fatalf("reply = %+v", msg)
}
events, ok := msg["events"].([]any)
if !ok || len(events) < 2 {
t.Fatalf("events = %#v, want at least the two written records", msg["events"])
}
// requireAuth writes a web.session.resume record for this same request, so
// that one legitimately appears newer. Assert the two written records are
// present and still newest-first relative to each other.
var names []string
for _, e := range events {
if m, ok := e.(map[string]any); ok {
names = append(names, auditquery.StringField(m, "event"))
}
}
joined := strings.Join(names, ",")
if !strings.Contains(joined, "remote.screen.start") || !strings.Contains(joined, "web.login.success") {
t.Fatalf("events = %v, want both written records", names)
}
if strings.Index(joined, "remote.screen.start") > strings.Index(joined, "web.login.success") {
t.Fatalf("events = %v, want newest-first order", names)
}
if msg["truncated"] != false || msg["file_exists"] != true {
t.Errorf("meta = %+v", msg)
}
}
func TestQueryAuditHandlerDisabledFile(t *testing.T) {
dir := t.TempDir()
wh, _ := newAuditTestHubWithoutAuditFile(t, dir)
admin, tok := auditTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{"token": tok})
wh.handleQueryAudit(admin, raw)
msg := readQueuedJSON(t, admin)
if msg["ok"] != false {
t.Fatalf("reply = %+v, want ok:false when the audit file is disabled", msg)
}
}