Files
SimpleRemoter/server/go/mcp/tools_local_test.go
T
yuanyuanxianganddeepseek-flash 3d18b2119a Fix(mcp): put listing rows and host ids into text blocks
MCP clients that surface only content[].text saw just count summaries from
list_hosts and get_audit_log; the 64-bit host id lived only in
structuredContent. Without the id, read_file, get_host_detail and
terminal_exec cannot be addressed, so the tools were unusable from those
clients.

Append a tab-separated table after the summary for every list-shaped local
tool: list_hosts (id first, then name/ip/group/os/online/clientType/
last_seen), get_audit_log (time/type/msg), list_files (drives and directory
entries) and get_host_detail (compact host JSON; id/ok/detail rows for a
batch call). Only the returned page is rendered, cells are flattened to one
line, and the truncation note stays on its own line before the table.

structuredContent is unchanged and remains the authoritative copy. Tests
cover row contents, paging, escaping and truncation ordering; a live run
against a Debug client confirmed the id is now visible in text. The MFC
server needs no equivalent change: BuildResult already appends the full
structuredContent as a second text item, so text-only clients there already
receive host ids. Go's envelope emits a single text item, which is why the
rows go into it.

Co-Authored-By: deepseek-flash
2026-11-13 11:25:57 +01:00

713 lines
24 KiB
Go

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 TestAppendRowsSanitizesCells(t *testing.T) {
got := appendRows("head", []string{"a", "b"},
[][]string{{"x\ty", "line\nbreak"}, {"", ""}})
want := "head\na\tb\nx y\tline break\n-\t-"
if got != want {
t.Fatalf("appendRows = %q, want %q", got, want)
}
if got := appendRows("head", []string{"a"}, nil); got != "head" {
t.Fatalf("empty rows = %q, want unchanged summary", got)
}
}
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)
}
// Text-only MCP clients never see structuredContent, so the table in the
// text block must carry the id every follow-up call is addressed by.
if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
t.Fatalf("text = %q, want host table header", text)
}
if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
t.Fatalf("text = %q, want ALPHA row with id first", 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)
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1001"}`)
if !strings.Contains(text, "\n") || !strings.Contains(text, `"id":"1001"`) ||
!strings.Contains(text, `"name":"ALPHA"`) {
t.Fatalf("text = %q, want summary plus host JSON", text)
}
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)
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","9999","2001"]}`)
if !strings.Contains(text, "id\tok\tdetail") ||
!strings.Contains(text, "1001\ttrue\t{") ||
!strings.Contains(text, "9999\tfalse\t") {
t.Fatalf("text = %q, want one row per id", text)
}
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})
text, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
if !strings.Contains(text, "time\ttype\tmsg") ||
!strings.Contains(text, "2026-11-12T10:03:00Z\tdevice.online\t") {
t.Fatalf("text = %q, want audit rows", text)
}
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")
}
}