package mcp import ( "context" "encoding/json" "os" "path/filepath" "strings" "sync" "testing" "github.com/yuanyuanxiang/SimpleRemoter/server/go/logger" ) // blockingListFiles installs a list_files handler that blocks while id == // blockID, so a second call for that host can be checked against the lock. func blockingListFiles(t *testing.T, s *Server, blockID string) (entered chan struct{}, release func()) { t.Helper() entered = make(chan struct{}) done := make(chan struct{}) var once sync.Once s.handlers["list_files"] = func(_ context.Context, args json.RawMessage) (any, *rpcError) { var a struct { ID string `json:"id"` } _ = json.Unmarshal(args, &a) if a.ID == blockID { once.Do(func() { close(entered) }) <-done } return newToolResult("ok", map[string]any{"id": a.ID}), nil } return entered, func() { close(done) } } func listFilesCall(t *testing.T, s *Server, id string) (any, *rpcError) { t.Helper() return s.callTool(context.Background(), json.RawMessage( `{"name":"list_files","arguments":{"id":"`+id+`","path":"/"}}`)) } func TestDeviceLockRejectsSecondCall(t *testing.T) { s := testServer(t, false) entered, release := blockingListFiles(t, s, "1001") type outcome struct { res any err *rpcError } first := make(chan outcome, 1) go func() { res, rerr := listFilesCall(t, s, "1001") first <- outcome{res, rerr} }() <-entered _, rerr := listFilesCall(t, s, "1001") if rerr == nil || rerr.Code != CodeBusy { t.Fatalf("second same-host call error = %+v, want -32003", rerr) } if !strings.Contains(rerr.Message, "tool=list_files") || !strings.Contains(rerr.Message, "elapsed=") { t.Fatalf("busy message = %q, want tool and elapsed", rerr.Message) } // A different host is a different lock and must not be blocked. if _, rerr = listFilesCall(t, s, "2002"); rerr != nil { t.Fatalf("other-host call error = %+v, want success", rerr) } release() if got := <-first; got.err != nil { t.Fatalf("first call error = %+v, want success", got.err) } // The lock is released once the call returns. if _, rerr = listFilesCall(t, s, "1001"); rerr != nil { t.Fatalf("call after release error = %+v, want success", rerr) } } func TestDeviceLockReleasedOnContextCancel(t *testing.T) { s := testServer(t, false) entered := make(chan struct{}) var once sync.Once s.handlers["list_files"] = func(ctx context.Context, _ json.RawMessage) (any, *rpcError) { once.Do(func() { close(entered) }) <-ctx.Done() return nil, errf(CodeTimeout, "request cancelled") } ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { defer close(done) _, _ = s.callTool(ctx, json.RawMessage( `{"name":"list_files","arguments":{"id":"1001"}}`)) }() <-entered cancel() <-done // Replace the cancelling handler before reusing the host: the lock must // already be free, and this handler returns immediately. s.handlers["list_files"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) { return newToolResult("ok", map[string]any{"id": "1001"}), nil } if _, rerr := listFilesCall(t, s, "1001"); rerr != nil { t.Fatalf("call after cancel error = %+v, want success (lock must be free)", rerr) } } func TestGlobalConcurrencyGate(t *testing.T) { log := logger.New(logger.Config{Level: logger.LevelError, File: filepath.Join(t.TempDir(), "mcp-test.log")}) t.Cleanup(func() { _ = log.Close() }) s := New(Config{Token: testToken, MaxConcurrency: 1, Log: log}) entered, release := blockingListFiles(t, s, "1001") type outcome struct { res any err *rpcError } first := make(chan outcome, 1) go func() { res, rerr := listFilesCall(t, s, "1001") first <- outcome{res, rerr} }() <-entered // A different host still needs a global slot, and there is only one. _, rerr := listFilesCall(t, s, "2002") if rerr == nil || rerr.Code != CodeBusy { t.Fatalf("second call error = %+v, want -32003", rerr) } if !strings.Contains(rerr.Message, "concurrent") { t.Fatalf("concurrency message = %q", rerr.Message) } release() if got := <-first; got.err != nil { t.Fatalf("first call error = %+v", got.err) } if _, rerr = listFilesCall(t, s, "2002"); rerr != nil { t.Fatalf("call after slot freed error = %+v, want success", rerr) } } // readAuditRecords returns the audit JSON lines written so far. func readAuditRecords(t *testing.T, path string) []map[string]any { t.Helper() data, err := os.ReadFile(path) if err != nil { t.Fatalf("read audit file: %v", err) } var out []map[string]any for line := range strings.SplitSeq(strings.TrimSpace(string(data)), "\n") { if line == "" { continue } var rec map[string]any if err := json.Unmarshal([]byte(line), &rec); err != nil { t.Fatalf("parse audit line %q: %v", line, err) } out = append(out, rec) } return out } func TestToolCallAudit(t *testing.T) { dir := t.TempDir() auditPath := filepath.Join(dir, "audit.log") log := logger.New(logger.Config{ Level: logger.LevelError, File: filepath.Join(dir, "server.log"), AuditFile: auditPath, }) t.Cleanup(func() { _ = log.Close() }) s := New(Config{Token: testToken, Log: log}) s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) { return newToolResult("done", map[string]any{"output": "secret-output"}), nil } text, _, rerr := callLocal(t, s, "terminal_exec", `{"id":"1001","command":"mysql -pTopSecret --batch"}`) if rerr != nil { t.Fatalf("terminal_exec error = %+v (text %q)", rerr, text) } if _, _, rerr = callLocal(t, s, "nope", `{}`); rerr == nil || rerr.Code != CodeMethodNotFound { t.Fatalf("unknown tool error = %+v, want -32601", rerr) } // A local tool has no device and must audit device "-". if _, _, rerr = callLocal(t, s, "get_server_status", `{}`); rerr != nil { t.Fatalf("get_server_status error = %+v", rerr) } recs := readAuditRecords(t, auditPath) if len(recs) != 3 { t.Fatalf("audit records = %d, want 3", len(recs)) } ok := recs[0] if ok["event"] != "mcp.tool.call" || ok["actor"] != "mcp" || ok["role"] != "admin" || ok["source"] != "mcp" { t.Fatalf("identity fields = %v", ok) } if ok["tool"] != "terminal_exec" || ok["device"] != "1001" { t.Fatalf("tool/device = %v/%v", ok["tool"], ok["device"]) } if ok["ok"] != true || ok["code"].(float64) != 0 { t.Fatalf("ok/code = %v/%v", ok["ok"], ok["code"]) } if _, hasMS := ok["ms"]; !hasMS { t.Fatal("missing ms") } args, _ := ok["args"].(string) if !strings.Contains(args, "mysql (len=") { t.Fatalf("args = %q, want first word + length", args) } if strings.Contains(args, "TopSecret") { t.Fatalf("args leaked the command body: %q", args) } if res, _ := ok["result"].(string); !strings.Contains(res, "bytes") { t.Fatalf("result = %q, want byte summary", res) } bad := recs[1] if bad["tool"] != "nope" || bad["ok"] != false || bad["code"].(float64) != CodeMethodNotFound { t.Fatalf("failed call record = %v", bad) } if bad["device"] != "-" { t.Fatalf("unknown tool device = %v, want -", bad["device"]) } if res, _ := bad["result"].(string); !strings.Contains(res, "unknown tool") { t.Fatalf("failure result = %q", res) } local := recs[2] if local["tool"] != "get_server_status" || local["device"] != "-" || local["ok"] != true { t.Fatalf("local tool record = %v", local) } } // A panicking handler must not take the connection down and must not be // audited as a success. func TestToolCallPanicAuditedAsFailure(t *testing.T) { dir := t.TempDir() auditPath := filepath.Join(dir, "audit.log") log := logger.New(logger.Config{ Level: logger.LevelError, File: filepath.Join(dir, "server.log"), AuditFile: auditPath, }) t.Cleanup(func() { _ = log.Close() }) s := New(Config{Token: testToken, Log: log}) s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) { panic("boom") } if _, rerr := s.callTool(context.Background(), json.RawMessage( `{"name":"terminal_exec","arguments":{"id":"1001","command":"dir"}}`)); rerr == nil || rerr.Code != CodeInternal { t.Fatalf("panic call error = %+v, want -32000", rerr) } recs := readAuditRecords(t, auditPath) if len(recs) != 1 { t.Fatalf("audit records = %d, want 1", len(recs)) } if recs[0]["ok"] != false || recs[0]["code"].(float64) != CodeInternal { t.Fatalf("panic record = %v, want ok=false code=-32000", recs[0]) } // The host lock must be free again despite the panic. s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) { return newToolResult("ok", nil), nil } if _, rerr := s.callTool(context.Background(), json.RawMessage( `{"name":"terminal_exec","arguments":{"id":"1001"}}`)); rerr != nil { t.Fatalf("call after panic error = %+v, want success", rerr) } } func TestSummarizeArgsRedactsSensitiveValues(t *testing.T) { got := summarizeArgs(json.RawMessage(`{ "id": "1001", "command": "mysql -pTopSecret --batch", "text": "hello secret", "message": "msg secret", "body": "{\"key\":\"secret\"}", "headers": {"Authorization": "Bearer tok"}, "password": "pw" }`)) for _, leak := range []string{"TopSecret", "hello secret", "msg secret", "Bearer tok", "pw"} { if strings.Contains(got, leak) { t.Fatalf("args leaked %q: %s", leak, got) } } if !strings.Contains(got, "mysql (len=") { t.Fatalf("command digest missing: %s", got) } if !strings.Contains(got, "redacted(") { t.Fatalf("redaction marker missing: %s", got) } if len(got) > auditArgsMaxBytes { t.Fatalf("digest = %d bytes, want <= %d", len(got), auditArgsMaxBytes) } // The ellipsis counts toward the cap. long := summarizeArgs(json.RawMessage(`{"note":"` + strings.Repeat("a", 800) + `"}`)) if len(long) > auditArgsMaxBytes || !strings.HasSuffix(long, "…") { t.Fatalf("truncated digest = %d bytes, tail %q", len(long), long[len(long)-3:]) } }