From b704258ba48eab5def4e5c3ee1962854f9037503 Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Thu, 19 Nov 2026 11:17:56 +0100 Subject: [PATCH] Feature: hide user-bound devices from MCP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 设备绑定到 Web 用户后,MCP 端点(静态 token,等同管理员凭证)仍能按 ID 操作,与"私人设备只归 owner"的模型冲突。按产品决定采用最严格策略:MCP 只面向公共设备,绑定设备对 MCP 一律不可见、不可达,即使知道 ID 也一样。 - list_hosts / get_host_detail / get_server_status 先过滤绑定设备再计数与 分页;离线列表用完整在线集合作差,避免在线私人设备以离线条目复现。 - 所有单主机工具在 callTool 统一拒绝(get_screenshot / list_files / read_file / terminal_exec / terminal_close 及将来新增工具),批量 ids 由 逐台执行处拒绝;后续新工具不会再漏。 - 拒绝返回与离线主机相同的 -32002 "Host not found or offline",不泄露设备 是否存在。 - get_audit_log 过滤 device_id / device / devices 中任意一个指向绑定设备的 记录;owner 快照一次取用,不逐条加锁。 - cmd 把 Web 的 DeviceACL 注入 MCP;未启用 ACL 时行为完全不变。 验证:go build/test/vet 全绿;新增 MCP 侧列表隐藏、按 ID 拒绝、批量拒绝、 状态计数、审计过滤(三种字段写法)测试。 Model: deepseek-flash Co-Authored-By: Claude Code --- server/go/cmd/main.go | 2 + server/go/mcp/device_acl_test.go | 185 +++++++++++++++++++++++++++++++ server/go/mcp/filemgr.go | 3 + server/go/mcp/server.go | 71 ++++++++++++ server/go/mcp/tools_local.go | 36 ++++-- server/go/mcp/tools_term.go | 1 - 6 files changed, 286 insertions(+), 12 deletions(-) create mode 100644 server/go/mcp/device_acl_test.go diff --git a/server/go/cmd/main.go b/server/go/cmd/main.go index 5e21bae..0b53ba3 100644 --- a/server/go/cmd/main.go +++ b/server/go/cmd/main.go @@ -1274,6 +1274,8 @@ func main() { AuditPath: auditFile, Port: *httpPort, Bind: bindAddr, + // Devices bound to a web user are invisible/unreachable through MCP. + DeviceACL: deviceACL, }) if mcpSrv.Enabled() { // Terminal tools need the hub's shell events (ready/data/closed). diff --git a/server/go/mcp/device_acl_test.go b/server/go/mcp/device_acl_test.go new file mode 100644 index 0000000..fa116d5 --- /dev/null +++ b/server/go/mcp/device_acl_test.go @@ -0,0 +1,185 @@ +package mcp + +import ( + "encoding/json" + "strings" + "testing" +) + +// fakeOwners stands in for web.DeviceACL: a device with a non-empty owner is +// bound to that web user and must be invisible to MCP. +type fakeOwners map[string]string + +func (f fakeOwners) Owner(deviceID string) string { return f[deviceID] } + +func bindOwners(s *Server, owners fakeOwners) { s.cfg.DeviceACL = owners } + +func hasID(hosts []map[string]any, id string) bool { + for _, h := range hosts { + if h["id"] == id { + return true + } + } + return false +} + +func wantNoID(t *testing.T, hosts []map[string]any, id string) { + t.Helper() + if hasID(hosts, id) { + t.Fatalf("ids = %v, must not contain bound device %s", hostIDs(hosts), id) + } +} + +// TestACLListHostsHidesBoundDevices covers the listing paths: online and +// offline entries whose owner is set are dropped before paging and counting, +// so they affect neither the page nor total/totalAll. +func TestACLListHostsHidesBoundDevices(t *testing.T) { + f := newLocalFixture(t) + bindOwners(f.srv, fakeOwners{"1001": "alice", "2001": "alice"}) + + _, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`) + hosts := hostList(t, sc) + wantIDs(t, hosts, "1002", "1003") + wantNoID(t, hosts, "1001") + if got := intField(t, sc, "total"); got != 2 { + t.Fatalf("total = %d, want 2 public hosts", got) + } + if got := intField(t, sc, "totalAll"); got != 2 { + t.Fatalf("totalAll = %d, want 2 public hosts", got) + } + + _, sc = mustCallLocal(t, f.srv, "list_hosts", `{"include_offline":true}`) + hosts = hostList(t, sc) + wantNoID(t, hosts, "1001") + wantNoID(t, hosts, "2001") // bound device that is now offline + if !hasID(hosts, "2002") { + t.Fatalf("ids = %v, want unbound offline device 2002", hostIDs(hosts)) + } + if got := intField(t, sc, "total"); got != 3 { + t.Fatalf("total = %d, want 3 public hosts (2 online + 1 offline)", got) + } + + // Filtering by the bound device's own name or group must not reveal it + // through an empty-but-otherwise-valid result either: the filters apply to + // the public snapshot, so the answer is simply nothing. + for _, q := range []string{`{"name":"ALPHA"}`, `{"query":"ALPHA"}`, `{"group":"Legacy"}`} { + if _, sc = mustCallLocal(t, f.srv, "list_hosts", q); len(hostList(t, sc)) != 0 { + t.Fatalf("%s returned bound hosts: %v", q, hostIDs(hostList(t, sc))) + } + } +} + +// TestACLDeniesBoundDeviceByID checks the per-device tools: a bound device is +// answered exactly like an offline host, so MCP callers cannot tell it exists +// at all (policy C: bound devices are unreachable even by id). +func TestACLDeniesBoundDeviceByID(t *testing.T) { + f := newLocalFixture(t) + bindOwners(f.srv, fakeOwners{"1001": "alice"}) + + single := []struct{ tool, args string }{ + {"get_host_detail", `{"id":"1001"}`}, + {"get_screenshot", `{"id":"1001"}`}, + {"list_files", `{"id":"1001"}`}, + {"read_file", `{"id":"1001","path":"/etc/hostname"}`}, + {"terminal_exec", `{"id":"1001","command":"dir"}`}, + } + for _, c := range single { + if _, _, rerr := callLocal(t, f.srv, c.tool, c.args); rerr == nil || rerr.Code != CodeOffline { + t.Fatalf("%s on bound device = %+v, want -32002", c.tool, rerr) + } + } + + // The batch form reports a per-id failure, not a leak. + text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","1002"]}`) + if got := intField(t, sc, "succeeded"); got != 1 { + t.Fatalf("succeeded = %d, want only the public host", got) + } + if got := intField(t, sc, "failed"); got != 1 { + t.Fatalf("failed = %d, want the bound host", got) + } + if strings.Contains(text, "ALPHA") { + t.Fatalf("text leaks the bound host: %q", text) + } + first := sc["results"].([]any)[0].(map[string]any) + if ok, _ := first["ok"].(bool); ok { + t.Fatalf("bound id reported ok: %v", first) + } + + // Files batch listing: every bound id fails, public ids still succeed. + _, sc = mustCallLocal(t, f.srv, "list_files", `{"ids":["1001"]}`) + raw, _ := json.Marshal(sc["results"]) + if !strings.Contains(string(raw), `"ok":false`) || strings.Contains(string(raw), "ALPHA") { + t.Fatalf("list_files batch = %s, want one opaque failure", raw) + } + + // The gate is the owner map, not the device's online state: an unbound id + // must still pass it (the later "is it online" check rejects 9999). + if f.srv.denyPrivateDevice("1002") != nil { + t.Fatal("unbound device denied") + } + if f.srv.denyPrivateDevice("9999") != nil { + t.Fatal("unknown device denied as private") + } +} + +// TestACLServerStatusCounts verifies the status tool counts only public +// devices, so bound hosts do not inflate the fleet summary. +func TestACLServerStatusCounts(t *testing.T) { + f := newLocalFixture(t) + bindOwners(f.srv, fakeOwners{"1001": "alice", "2001": "alice"}) + + _, sc := mustCallLocal(t, f.srv, "get_server_status", `{}`) + hosts, ok := sc["hosts"].(map[string]any) + if !ok { + t.Fatalf("hosts = %v", sc["hosts"]) + } + if got := intField(t, hosts, "online"); got != 2 { + t.Fatalf("online = %d, want 2 public online hosts", got) + } + if got := intField(t, hosts, "offline"); got != 1 { + t.Fatalf("offline = %d, want 1 public offline host", got) + } +} + +// TestACLAuditHidesBoundDeviceRecords checks that audit records carrying a +// bound device_id are filtered out of get_audit_log, including through +// keyword/type filters, while the pre-filter total stays honest. +func TestACLAuditHidesBoundDeviceRecords(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":"device.online","device_id":"1001","name":"ALPHA"}`, + `{"audit":true,"time":"2026-11-12T10:02:00Z","level":"info","event":"device.online","device_id":"1002","name":"BETA"}`, + // MCP tool calls spell the target as "device". + `{"audit":true,"time":"2026-11-12T10:03:00Z","level":"info","event":"mcp.tool.call","device":"1001","args":"{}"}`, + // Bind/unbind records carry a devices array. + `{"audit":true,"time":"2026-11-12T10:04:00Z","level":"info","event":"admin.device.bind","devices":["1001","1002"],"owner":"alice"}`, + ) + s := New(Config{Token: "test-token", AuditPath: path}) + bindOwners(s, fakeOwners{"1001": "alice"}) + + text, sc := mustCallLocal(t, s, "get_audit_log", `{}`) + // Public: login, device.online 1002. Hidden: device_id 1001, MCP device + // 1001, and the bind record because its devices array names 1001. + if got := intField(t, sc, "total"); got != 2 { + t.Fatalf("total = %d, want the two public records", got) + } + if got := intField(t, sc, "totalAll"); got != 5 { + t.Fatalf("totalAll = %d, want unfiltered 5", got) + } + for _, leak := range []string{"ALPHA", `"device_id":"1001"`, `"device":"1001"`, `"devices":["1001"`} { + if strings.Contains(text, leak) { + t.Fatalf("text leaks bound-device record %s: %q", leak, text) + } + } + + // A keyword carried only by the bound device's record finds nothing. + if _, sc = mustCallLocal(t, s, "get_audit_log", `{"keyword":"ALPHA"}`); intField(t, sc, "total") != 0 { + t.Fatalf("keyword ALPHA total = %d, want 0", intField(t, sc, "total")) + } + + // Without an owner map (MCP-only deployments) nothing is filtered. + plain := New(Config{Token: "test-token", AuditPath: path}) + if _, sc = mustCallLocal(t, plain, "get_audit_log", `{}`); intField(t, sc, "total") != 5 { + t.Fatalf("no-ACL total = %d, want 5", intField(t, sc, "total")) + } +} diff --git a/server/go/mcp/filemgr.go b/server/go/mcp/filemgr.go index 50a5f83..201d3eb 100644 --- a/server/go/mcp/filemgr.go +++ b/server/go/mcp/filemgr.go @@ -511,6 +511,9 @@ func (s *Server) listFilesOne(ctx context.Context, args listFilesArgs) (toolResu if !isDecimalID(args.ID) { return toolResult{}, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string") } + if rerr := s.denyPrivateDevice(args.ID); rerr != nil { + return toolResult{}, rerr + } // NUL and newlines would truncate or split the client's C string field. if strings.ContainsAny(args.Path, "\x00\r\n") { return toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed") diff --git a/server/go/mcp/server.go b/server/go/mcp/server.go index f6bf2a7..93f6937 100644 --- a/server/go/mcp/server.go +++ b/server/go/mcp/server.go @@ -36,6 +36,34 @@ const ( termSweepInterval = 30 * time.Second ) +// DeviceOwner reports the owner of a device. The web console's DeviceACL +// implements it; declared here as an interface so the MCP package does not +// import the web package. +type DeviceOwner interface { + Owner(deviceID string) string +} + +// deviceOwnerSnapshotter is an optional DeviceOwner capability: returning the +// whole binding table lets a long operation (the audit scan) apply the policy +// without a read-lock acquisition per record. Implemented by web.DeviceACL. +type deviceOwnerSnapshotter interface { + Owners() map[string]string +} + +// ownerChecker returns a predicate for "is this device public?" that borrows a +// single snapshot when the ACL supports it, so scanning thousands of audit +// records does not contend with an in-flight bind's write lock. +func (s *Server) ownerChecker() func(deviceID string) bool { + if s.cfg.DeviceACL == nil { + return nil + } + if snap, ok := s.cfg.DeviceACL.(deviceOwnerSnapshotter); ok { + owners := snap.Owners() + return func(id string) bool { return owners[id] == "" } + } + return func(id string) bool { return s.cfg.DeviceACL.Owner(id) == "" } +} + // Config is filled by cmd/main.go from the YAMA_MCP_* environment variables; // the package itself never reads the environment, so tests are deterministic. type Config struct { @@ -56,6 +84,12 @@ type Config struct { 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 + + // DeviceACL, when non-nil, hides devices bound to a web user. MCP only + // operates public devices (product decision): a bound device is invisible + // in list_hosts/get_host_detail and unreachable by ID in every device- + // targeted tool, even if its ID is known. + DeviceACL DeviceOwner } // toolFunc implements one tools/call. It returns either a result value or a @@ -145,6 +179,36 @@ func New(cfg Config) *Server { // unknown path. func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" } +// devicePrivate reports whether the device is bound to a web user. MCP only +// operates public devices; bound devices are hidden and unreachable here even +// though the endpoint's static token is effectively an admin credential. +func (s *Server) devicePrivate(deviceID string) bool { + return s.cfg.DeviceACL != nil && s.cfg.DeviceACL.Owner(deviceID) != "" +} + +// denyPrivateDevice returns the same error shape as an offline host so a +// private device is indistinguishable from one that does not exist. +func (s *Server) denyPrivateDevice(deviceID string) *rpcError { + if s.devicePrivate(deviceID) { + return errf(CodeOffline, "Host not found or offline: %s", deviceID) + } + return nil +} + +// publicDevices filters a device snapshot down to the ones MCP may expose. +func (s *Server) publicDevices(devices []hub.DeviceInfo) []hub.DeviceInfo { + if s.cfg.DeviceACL == nil { + return devices + } + out := make([]hub.DeviceInfo, 0, len(devices)) + for _, d := range devices { + if s.cfg.DeviceACL.Owner(d.ID) == "" { + out = append(out, d) + } + } + return out +} + // Close releases resources held by long-lived tool state: the reaper stops and // every terminal session MCP owns is torn down and the shell told to exit. func (s *Server) Close() { @@ -344,6 +408,13 @@ func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (result any, // a temporary state between milestones, not a client mistake. return nil, errf(CodeInternal, "tool %s is not implemented by this server build", params.Name) } + // A device bound to a web user is invisible to MCP (product policy). Enforce + // it once here for every single-host tool so a new tool cannot forget the + // check; batch id[] spellings are checked by their per-host handler + // (listFilesOne / hostMaps). + if rerr := s.denyPrivateDevice(deviceID); rerr != nil { + return nil, rerr + } // Global slot first: a call that would be rejected for concurrency must // not squat on a device lock while it fails. diff --git a/server/go/mcp/tools_local.go b/server/go/mcp/tools_local.go index 3fd1ee1..84b9b59 100644 --- a/server/go/mcp/tools_local.go +++ b/server/go/mcp/tools_local.go @@ -106,12 +106,17 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp } includeOffline := args.IncludeOffline != nil && *args.IncludeOffline - onlineDevices := s.cfg.Hub.ListDevices() - onlineSet := make(map[string]struct{}, len(onlineDevices)) - for _, d := range onlineDevices { + // The offline history must be computed from the FULL online set, not the + // ACL-filtered one: otherwise a private device that is currently online + // would reappear as an "offline" entry until the outer filter drops it. + // Filter once, at the end. + onlineAll := s.cfg.Hub.ListDevices() + onlineSet := make(map[string]struct{}, len(onlineAll)) + for _, d := range onlineAll { onlineSet[d.ID] = struct{}{} } - offlineDevices := s.offlineDevices(onlineSet) + onlineDevices := s.publicDevices(onlineAll) + offlineDevices := s.publicDevices(s.offlineDevices(onlineSet)) var pool []hub.DeviceInfo switch { @@ -347,14 +352,19 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) { // 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() + onlineAll := s.cfg.Hub.ListDevices() + onlineSet := make(map[string]struct{}, len(onlineAll)) + onlineDevices := s.publicDevices(onlineAll) online = make(map[string]hub.DeviceInfo, len(onlineDevices)) - onlineSet := make(map[string]struct{}, len(onlineDevices)) for _, d := range onlineDevices { online[d.ID] = d + } + // Derive offline entries from the full online set (see callListHosts): + // a private online device must not be mistaken for an offline one. + for _, d := range onlineAll { onlineSet[d.ID] = struct{}{} } - offlineDevices := s.offlineDevices(onlineSet) + offlineDevices := s.publicDevices(s.offlineDevices(onlineSet)) offline = make(map[string]hub.DeviceInfo, len(offlineDevices)) for _, d := range offlineDevices { offline[d.ID] = d @@ -483,12 +493,13 @@ func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any, 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 { + onlineAll := s.cfg.Hub.ListDevices() + onlineSet := make(map[string]struct{}, len(onlineAll)) + for _, d := range onlineAll { onlineSet[d.ID] = struct{}{} } - offline := len(s.offlineDevices(onlineSet)) + onlineDevices := s.publicDevices(onlineAll) + offline := len(s.publicDevices(s.offlineDevices(onlineSet))) status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline} text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline) } @@ -530,6 +541,9 @@ func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, * // event name; the web UI's exact/prefix Event filter does not fit. EventContains: args.Type, } + // Audit records name their target device. A device bound to a web user is + // invisible to MCP, so its activity must not leak through the log either. + q.DeviceAllowed = s.ownerChecker() q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit) q.Offset = auditquery.ClampOffset(args.Offset) diff --git a/server/go/mcp/tools_term.go b/server/go/mcp/tools_term.go index 694cad7..40b2b95 100644 --- a/server/go/mcp/tools_term.go +++ b/server/go/mcp/tools_term.go @@ -131,7 +131,6 @@ func (s *Server) callTerminalExec(ctx context.Context, raw json.RawMessage) (any if !isDecimalID(args.ID) { return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string") } - command := strings.TrimSpace(args.Command) isPoll := command == "" if isPoll && args.SessionID == "" {