diff --git a/api/policy.go b/api/policy.go index 755aec2eb..2de515349 100644 --- a/api/policy.go +++ b/api/policy.go @@ -54,6 +54,12 @@ type NodeConfig struct { // together and mean opposite directions. Labels map[string]string `yaml:"labels,omitempty"` Egress Egress `yaml:"egress"` + Audit AuditConfig `yaml:"audit,omitempty"` +} + +// AuditConfig holds optional audit logging configuration for the node. +type AuditConfig struct { + CallLogPath string `yaml:"call_log_path,omitempty"` } // NodeConfigVersionV1Alpha1 is the only node config schema this build understands. diff --git a/cmd/agentmesh-node/main.go b/cmd/agentmesh-node/main.go index 798f1afb7..e4713d2df 100644 --- a/cmd/agentmesh-node/main.go +++ b/cmd/agentmesh-node/main.go @@ -112,6 +112,7 @@ var ( secretsDirFlag string controlPlaneSyncIntervalFlag time.Duration cloudProviderFlag string + callAuditLogPathFlag string ) var logger = golog.Logger("agentmesh-node-cli") @@ -322,6 +323,9 @@ func main() { if jwtFlag != "" { logger.Warn("--jwt passes a secret on the command line; prefer --jwt-path") } + if callAuditLogPathFlag == "" { + callAuditLogPathFlag = os.Getenv("AGENTMESH_CALL_AUDIT_LOG_PATH") + } store, err := node.NewStore(resolveDataDir()) if err != nil { @@ -468,6 +472,7 @@ func main() { DiscoveryConcurrency: discoveryConcurrencyFlag, BackendProbeTimeout: backendProbeTimeoutFlag, SecretsDir: secretsDirFlag, + CallAuditLogPath: callAuditLogPathFlag, } } @@ -892,6 +897,7 @@ func main() { runCmd.Flags().DurationVar(&controlPlaneSyncIntervalFlag, "control-plane-sync-interval", node.DefaultControlPlaneSyncInterval, "How often signing keys, bans, router addresses and mesh policy are pulled from the control plane. Keep it well below the control plane's --key-grace-period; raise it on large meshes.") runCmd.Flags().DurationVar(&backendProbeTimeoutFlag, "backend-probe-timeout", 0, "Timeout for probing a command-spawned service backend before advertising it (0 uses default 2s); raise this for backends with slower cold-start times") runCmd.Flags().StringVar(&secretsDirFlag, "secrets-dir", node.DefaultSecretsDir, "Directory holding the credentials named by the control plane's egress destinations, one file per credential name") + runCmd.Flags().StringVar(&callAuditLogPathFlag, "call-audit-log-path", "", "Path to file for structured call audit logging (JSONL); stdout and stderr write to process streams (default: disabled, or env AGENTMESH_CALL_AUDIT_LOG_PATH)") rootCmd.PersistentFlags().StringVar(&controlPlaneAddr, "control-plane", "", "Control plane URL") rootCmd.PersistentFlags().BoolVar(&insecureControlPlaneFlag, "insecure-control-plane", false, "Accept a plaintext http:// control plane URL to a non-loopback host (whoever answers it becomes this node's trust root; only for networks you already trust)") rootCmd.PersistentFlags().StringVar(&configFile, "config", node.DefaultConfigFile, "Path to agentmesh-node.yaml configuration file") diff --git a/cmd/agentmesh-router/main.go b/cmd/agentmesh-router/main.go index 5b702fe1a..114c26f45 100644 --- a/cmd/agentmesh-router/main.go +++ b/cmd/agentmesh-router/main.go @@ -82,6 +82,7 @@ var ( ingressTLSKeyPath string allowInsecureIngressHTTP bool publicControlPlaneURL string + callAuditLogPath string ) var logger = golog.Logger("agentmesh-router-cli") @@ -94,6 +95,10 @@ func main() { Run: func(cmd *cobra.Command, args []string) { logging.Setup(logging.Options{Level: logLevel, Format: logFormat}) + if callAuditLogPath == "" { + callAuditLogPath = os.Getenv("AGENTMESH_CALL_AUDIT_LOG_PATH") + } + opts := router.Options{ ControlPlaneURL: controlPlaneURL, AllowInsecureControlPlane: insecureControlPlane, @@ -122,6 +127,7 @@ func main() { IngressTLSKeyPath: ingressTLSKeyPath, AllowInsecureIngressHTTP: allowInsecureIngressHTTP, PublicControlPlaneURL: publicControlPlaneURL, + CallAuditLogPath: callAuditLogPath, } labels, err := api.ParseLabelFlags(labelFlags) if err != nil { @@ -187,6 +193,7 @@ func main() { rootCmd.Flags().StringVar(&ingressTLSKeyPath, "ingress-tls-key-path", "", "Path to TLS private key file for --ingress-addr") rootCmd.Flags().BoolVar(&allowInsecureIngressHTTP, "allow-insecure-ingress-http", false, "Allow --ingress-addr on a non-loopback interface without TLS and allow http:// in --ingress-url. Risk: every caller's bearer Biscuit and request body then cross the network in plaintext between the client and this router; set it only when a TLS-terminating L7 load balancer in front of the router is the only thing that can reach --ingress-addr") rootCmd.Flags().StringVar(&publicControlPlaneURL, "public-control-plane", "", "Optional public URL of the control plane advertised in RFC 9728 and A2A OAuth metadata when --control-plane uses a cluster-internal address") + rootCmd.Flags().StringVar(&callAuditLogPath, "call-audit-log-path", "", "Path to file for structured call audit logging (JSONL); stdout and stderr write to process streams (default: disabled, or env AGENTMESH_CALL_AUDIT_LOG_PATH)") ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer cancel() diff --git a/internal/audit/audit.go b/internal/audit/audit.go new file mode 100644 index 000000000..de471f963 --- /dev/null +++ b/internal/audit/audit.go @@ -0,0 +1,176 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package audit provides optional metadata-only call audit logging for tool +// invocations across mesh nodes and routers. +// +// Payloads, prompts, arguments, results, response bodies, credentials and tokens +// are strictly excluded by design. +package audit + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sync" + "time" + + "github.com/google/agentmesh/api" + golog "github.com/ipfs/go-log/v2" + "github.com/modelcontextprotocol/go-sdk/jsonrpc" +) + +var logger = golog.Logger("audit") + +// Standard outcome classes for call audit records. +// Sensitive details or raw backend error messages must never be placed in outcome. +const ( + OutcomeOK = "ok" + OutcomeUnauthorized = "unauthorized" + OutcomeInvalidParams = "invalid_params" + OutcomeNotFound = "not_found" + OutcomeTimeout = "timeout" + OutcomeCancelled = "cancelled" + OutcomeRateLimited = "rate_limited" + OutcomeToolError = "tool_error" + OutcomeBackendError = "backend_error" + OutcomeBadGateway = "bad_gateway" + OutcomeForbidden = "forbidden" + OutcomeCallFailed = "call_failed" + OutcomeLabelsNotSatisfied = "labels_not_satisfied" + OutcomeProviderNotGranted = "provider_not_granted" + OutcomeError = "error" +) + +// Record is a single structured JSONL tool call audit record. +// Deliberately captures only call metadata. Payloads, arguments, prompts, results, +// response bodies, and credentials are intentionally excluded. +type Record struct { + Timestamp string `json:"timestamp"` + CallerPeerID string `json:"caller_peer_id"` + CallerLabels map[string]string `json:"caller_labels,omitempty"` + ProviderPeerID string `json:"provider_peer_id"` + ServiceName string `json:"service_name"` + ToolName string `json:"tool_name"` + Outcome string `json:"outcome"` + LatencyMS float64 `json:"latency_ms"` + BytesIn int64 `json:"bytes_in"` + BytesOut int64 `json:"bytes_out"` +} + +// Logger writes audit records as atomic JSONL lines to a sink. +type Logger struct { + mu sync.Mutex + out io.Writer + closer io.Closer +} + +// New creates a Logger writing to w. Nil w returns nil (disabled). +func New(w io.Writer) *Logger { + if w == nil { + return nil + } + return &Logger{out: w} +} + +// NewFromFile opens the given path for appending JSONL records. +// Special path values "stdout" and "-" write to os.Stdout; "stderr" writes to os.Stderr. +// An empty path returns nil (disabled). +func NewFromFile(path string) (*Logger, error) { + if path == "" { + return nil, nil + } + switch path { + case "stdout", "-": + return &Logger{out: os.Stdout}, nil + case "stderr": + return &Logger{out: os.Stderr}, nil + default: + dir := filepath.Dir(path) + if dir != "" && dir != "." { + if err := os.MkdirAll(dir, 0750); err != nil { + return nil, fmt.Errorf("create audit log directory %q: %w", dir, err) + } + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + if err != nil { + return nil, fmt.Errorf("open audit log file %q: %w", path, err) + } + return &Logger{out: f, closer: f}, nil + } +} + +// Log writes an audit record as a single JSONL line. +// Safe for concurrent use. Failures to write are caught and swallowed so they never +// break tool execution. +func (l *Logger) Log(rec Record) { + if l == nil { + return + } + defer func() { + _ = recover() + }() + + if rec.Timestamp == "" { + rec.Timestamp = time.Now().UTC().Format(time.RFC3339Nano) + } + + data, err := json.Marshal(rec) + if err != nil { + logger.Debugf("failed to marshal audit record: %v", err) + return + } + data = append(data, '\n') + + l.mu.Lock() + defer l.mu.Unlock() + if l.out != nil { + if _, writeErr := l.out.Write(data); writeErr != nil { + logger.Debugf("failed to write audit record: %v", writeErr) + } + } +} + +// Close flushes and closes the underlying file if opened by NewFromFile. +func (l *Logger) Close() error { + if l == nil { + return nil + } + l.mu.Lock() + defer l.mu.Unlock() + if l.closer != nil { + return l.closer.Close() + } + return nil +} + +// ClassifyJSONRPCError maps a JSON-RPC error code to a safe, standardized outcome class. +func ClassifyJSONRPCError(code int64) string { + switch code { + case api.JSONRPCCodeUnauthorized: + return OutcomeUnauthorized + case jsonrpc.CodeInvalidParams: + return OutcomeInvalidParams + case jsonrpc.CodeMethodNotFound: + return OutcomeNotFound + case jsonrpc.CodeInvalidRequest, jsonrpc.CodeParseError: + return OutcomeInvalidParams + case jsonrpc.CodeInternalError: + return OutcomeBackendError + default: + return OutcomeError + } +} diff --git a/internal/audit/audit_test.go b/internal/audit/audit_test.go new file mode 100644 index 000000000..fb44f6f2b --- /dev/null +++ b/internal/audit/audit_test.go @@ -0,0 +1,277 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package audit + +import ( + "bytes" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/google/agentmesh/api" + "github.com/modelcontextprotocol/go-sdk/jsonrpc" +) + +func TestDisabledByDefault(t *testing.T) { + var l *Logger + // Calling Log or Close on a nil logger must not panic and must do nothing. + l.Log(Record{ + CallerPeerID: "12D3KooWCaller", + ProviderPeerID: "12D3KooWProvider", + ServiceName: "calculator", + ToolName: "add", + Outcome: OutcomeOK, + }) + if err := l.Close(); err != nil { + t.Fatalf("Close on nil logger returned error: %v", err) + } + + fromEmpty, err := NewFromFile("") + if err != nil { + t.Fatalf("NewFromFile(\"\") returned error: %v", err) + } + if fromEmpty != nil { + t.Fatalf("NewFromFile(\"\") returned non-nil logger: %v", fromEmpty) + } +} + +func TestRecordFormattingAndExclusions(t *testing.T) { + var buf bytes.Buffer + l := New(&buf) + + rec := Record{ + Timestamp: "2026-11-28T13:00:00Z", + CallerPeerID: "12D3KooWCaller1111111111111111111111111111111111111", + CallerLabels: map[string]string{"region": "us-east-1", "tier": "gold"}, + ProviderPeerID: "12D3KooWProvider22222222222222222222222222222222222", + ServiceName: "code-reviewer", + ToolName: "review_pr", + Outcome: OutcomeOK, + LatencyMS: 124.5, + BytesIn: 512, + BytesOut: 1024, + } + + l.Log(rec) + + out := buf.String() + if !strings.HasSuffix(out, "\n") { + t.Fatalf("expected newline at end of record, got %q", out) + } + + var parsed map[string]any + if err := json.Unmarshal([]byte(out), &parsed); err != nil { + t.Fatalf("failed to parse JSONL output: %v", err) + } + + // Verify all expected metadata fields are present. + expectedFields := []string{ + "timestamp", + "caller_peer_id", + "caller_labels", + "provider_peer_id", + "service_name", + "tool_name", + "outcome", + "latency_ms", + "bytes_in", + "bytes_out", + } + for _, f := range expectedFields { + if _, ok := parsed[f]; !ok { + t.Errorf("missing expected field %q in audit record", f) + } + } + + // Verify values + if parsed["caller_peer_id"] != rec.CallerPeerID { + t.Errorf("got caller_peer_id %v, want %v", parsed["caller_peer_id"], rec.CallerPeerID) + } + if parsed["provider_peer_id"] != rec.ProviderPeerID { + t.Errorf("got provider_peer_id %v, want %v", parsed["provider_peer_id"], rec.ProviderPeerID) + } + if parsed["service_name"] != rec.ServiceName { + t.Errorf("got service_name %v, want %v", parsed["service_name"], rec.ServiceName) + } + if parsed["tool_name"] != rec.ToolName { + t.Errorf("got tool_name %v, want %v", parsed["tool_name"], rec.ToolName) + } + if parsed["outcome"] != OutcomeOK { + t.Errorf("got outcome %v, want %v", parsed["outcome"], OutcomeOK) + } + if parsed["bytes_in"] != float64(512) { + t.Errorf("got bytes_in %v, want 512", parsed["bytes_in"]) + } + if parsed["bytes_out"] != float64(1024) { + t.Errorf("got bytes_out %v, want 1024", parsed["bytes_out"]) + } + + // Verify that forbidden payload content is strictly absent. + forbiddenKeys := []string{ + "arguments", "args", "params", "prompt", "result", "content", + "response", "body", "token", "biscuit", "secret", "password", "headers", + } + for _, k := range forbiddenKeys { + if _, ok := parsed[k]; ok { + t.Errorf("forbidden payload field %q found in audit record", k) + } + } +} + +func TestConcurrentAuditEvents(t *testing.T) { + var buf bytes.Buffer + l := New(&buf) + + const concurrency = 50 + var wg sync.WaitGroup + wg.Add(concurrency) + + for i := 0; i < concurrency; i++ { + go func(idx int) { + defer wg.Done() + l.Log(Record{ + CallerPeerID: "12D3KooWCaller", + ProviderPeerID: "12D3KooWProvider", + ServiceName: "math-service", + ToolName: "calculate", + Outcome: OutcomeOK, + LatencyMS: float64(idx), + BytesIn: int64(idx * 10), + BytesOut: int64(idx * 20), + }) + }(i) + } + + wg.Wait() + + lines := strings.Split(strings.TrimSpace(buf.String()), "\n") + if len(lines) != concurrency { + t.Fatalf("expected %d audit lines, got %d", concurrency, len(lines)) + } + + for i, line := range lines { + var r Record + if err := json.Unmarshal([]byte(line), &r); err != nil { + t.Fatalf("line %d is not valid JSON: %v (content: %q)", i, err, line) + } + if r.ToolName != "calculate" || r.ServiceName != "math-service" { + t.Errorf("line %d has invalid content: %+v", i, r) + } + } +} + +type errWriter struct{} + +func (e *errWriter) Write(p []byte) (n int, err error) { + return 0, errors.New("simulated disk write failure") +} + +func TestLoggingFailureDoesNotBreakToolExecution(t *testing.T) { + l := New(&errWriter{}) + // Logging with a failing writer must not panic or cause an unhandled error. + l.Log(Record{ + CallerPeerID: "12D3KooWCaller", + ProviderPeerID: "12D3KooWProvider", + ServiceName: "critical-service", + ToolName: "execute", + Outcome: OutcomeOK, + }) +} + +func TestClassifyJSONRPCError(t *testing.T) { + cases := []struct { + code int64 + want string + }{ + {api.JSONRPCCodeUnauthorized, OutcomeUnauthorized}, + {jsonrpc.CodeInvalidParams, OutcomeInvalidParams}, + {jsonrpc.CodeMethodNotFound, OutcomeNotFound}, + {jsonrpc.CodeInvalidRequest, OutcomeInvalidParams}, + {jsonrpc.CodeParseError, OutcomeInvalidParams}, + {jsonrpc.CodeInternalError, OutcomeBackendError}, + {-99999, OutcomeError}, + } + for _, tc := range cases { + got := ClassifyJSONRPCError(tc.code) + if got != tc.want { + t.Errorf("ClassifyJSONRPCError(%d) = %q, want %q", tc.code, got, tc.want) + } + } +} + +func TestNewFromFile(t *testing.T) { + tmpDir := t.TempDir() + logPath := filepath.Join(tmpDir, "audit", "calls.jsonl") + + l, err := NewFromFile(logPath) + if err != nil { + t.Fatalf("NewFromFile failed: %v", err) + } + defer func() { _ = l.Close() }() + + l.Log(Record{ + CallerPeerID: "12D3KooW1", + ProviderPeerID: "12D3KooW2", + ServiceName: "echo", + ToolName: "ping", + Outcome: OutcomeOK, + LatencyMS: 5.2, + }) + + if err := l.Close(); err != nil { + t.Fatalf("Close failed: %v", err) + } + + data, err := os.ReadFile(logPath) + if err != nil { + t.Fatalf("read log file: %v", err) + } + if !strings.Contains(string(data), `"tool_name":"ping"`) { + t.Fatalf("expected log to contain ping tool call, got %s", string(data)) + } + + info, err := os.Stat(logPath) + if err != nil { + t.Fatalf("stat log file: %v", err) + } + // Check file permissions are 0600 + if perm := info.Mode().Perm(); perm != 0600 { + t.Errorf("expected 0600 permissions, got %#o", perm) + } +} + +func TestDefaultTimestamp(t *testing.T) { + var buf bytes.Buffer + l := New(&buf) + l.Log(Record{ + CallerPeerID: "12D3KooWCaller", + ToolName: "test", + }) + var r Record + if err := json.Unmarshal(buf.Bytes(), &r); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if r.Timestamp == "" { + t.Fatal("expected timestamp to be populated automatically when empty") + } + if _, err := time.Parse(time.RFC3339Nano, r.Timestamp); err != nil { + t.Fatalf("timestamp %q is not RFC3339: %v", r.Timestamp, err) + } +} diff --git a/internal/node/config.go b/internal/node/config.go index 1a66ea843..2335ca6df 100644 --- a/internal/node/config.go +++ b/internal/node/config.go @@ -44,6 +44,9 @@ type NodeConfigComplete struct { // means no floor, so a caller's requirement — or the absence of one — // stands on its own, as it always has. EgressRequireLabels map[string]string + + // CallAuditLogPath is the optional file path for structured JSONL tool call audit log. + CallAuditLogPath string } // LoadNodeConfig loads the node configuration from the specified path. @@ -98,6 +101,7 @@ func CompleteNodeConfig(config api.NodeConfig) (*NodeConfigComplete, error) { Services: config.Services, Labels: config.Labels, RequireTaskScope: config.Attenuation.RequireTaskScope, + CallAuditLogPath: config.Audit.CallLogPath, } if rawTTL := strings.TrimSpace(config.Attenuation.MaxTaskTTL); rawTTL != "" { diff --git a/internal/node/gate.go b/internal/node/gate.go index 790009aec..21f019fc0 100644 --- a/internal/node/gate.go +++ b/internal/node/gate.go @@ -87,6 +87,12 @@ func (n *AgentMeshNode) HandleMCPStream(s network.Stream, reqCtx RequestContext) if t, err := api.ParseServiceType(targetType); err == nil && t == api.ServiceType_SERVICE_TYPE_MCP { if svc, ok := n.services.GetTyped(t, targetName); ok { if mcpSvc, isMcp := svc.(*MCPService); isMcp { + if reqCtx.AuditLogger == nil { + reqCtx.AuditLogger = n.callAuditLogger + } + if reqCtx.ProviderPeerID == "" && n.Host != nil { + reqCtx.ProviderPeerID = n.Host.ID() + } mcpSvc.HandleStreamPassThrough(s, reqCtx) return } diff --git a/internal/node/mcp.go b/internal/node/mcp.go index abc538d22..cebbc11d9 100644 --- a/internal/node/mcp.go +++ b/internal/node/mcp.go @@ -26,6 +26,7 @@ import ( "time" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/peerstore" @@ -209,8 +210,46 @@ func (n *AgentMeshNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, too return nil, err } + var startTime time.Time + var callerID string + var callerLabels map[string]string + providerID := targetPeer.String() + if n.callAuditLogger != nil { + startTime = time.Now() + if n.Host != nil { + callerID = n.Host.ID().String() + } + callerLabels = n.ownAttestedLabels() + } + session, cleanup, err := n.connectMCPSessionWithRetry(ctx, targetPeer, targetService, requiredLabels) if err != nil { + if n.callAuditLogger != nil { + outcome := audit.OutcomeCallFailed + if errors.Is(err, ErrAuthRejected) { + outcome = audit.OutcomeUnauthorized + } else if errors.Is(err, ErrLabelsNotSatisfied) { + outcome = audit.OutcomeLabelsNotSatisfied + } else if errors.Is(err, ErrProviderNotGranted) { + outcome = audit.OutcomeProviderNotGranted + } else if errors.Is(err, context.DeadlineExceeded) || strings.Contains(err.Error(), "context deadline exceeded") { + outcome = audit.OutcomeTimeout + } else if errors.Is(err, context.Canceled) { + outcome = audit.OutcomeCancelled + } + n.callAuditLogger.Log(audit.Record{ + Timestamp: startTime.UTC().Format(time.RFC3339Nano), + CallerPeerID: callerID, + CallerLabels: callerLabels, + ProviderPeerID: providerID, + ServiceName: targetService, + ToolName: originalToolName, + Outcome: outcome, + LatencyMS: float64(time.Since(startTime).Microseconds()) / 1000.0, + BytesIn: 0, + BytesOut: 0, + }) + } return nil, err } defer cleanup() @@ -222,7 +261,48 @@ func (n *AgentMeshNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, too Arguments: params, } + var bytesOut int64 + if n.callAuditLogger != nil { + if callParamsBytes, mErr := json.Marshal(callParams); mErr == nil { + bytesOut = int64(len(callParamsBytes)) + } + } + res, err := session.CallTool(ctx, callParams) + + if n.callAuditLogger != nil { + var bytesIn int64 + if res != nil { + if resBytes, mErr := json.Marshal(res); mErr == nil { + bytesIn = int64(len(resBytes)) + } + } + outcome := audit.OutcomeOK + if err != nil { + outcome = audit.OutcomeCallFailed + if errors.Is(err, context.DeadlineExceeded) || strings.Contains(err.Error(), "context deadline exceeded") { + outcome = audit.OutcomeTimeout + } else if errors.Is(err, context.Canceled) { + outcome = audit.OutcomeCancelled + } + } else if res != nil && res.IsError { + outcome = audit.OutcomeToolError + } + + n.callAuditLogger.Log(audit.Record{ + Timestamp: startTime.UTC().Format(time.RFC3339Nano), + CallerPeerID: callerID, + CallerLabels: callerLabels, + ProviderPeerID: providerID, + ServiceName: targetService, + ToolName: originalToolName, + Outcome: outcome, + LatencyMS: float64(time.Since(startTime).Microseconds()) / 1000.0, + BytesIn: bytesIn, + BytesOut: bytesOut, + }) + } + if err != nil { return nil, fmt.Errorf("failed to call tool %s: %w", toolName, err) } diff --git a/internal/node/mcp_audit_test.go b/internal/node/mcp_audit_test.go new file mode 100644 index 000000000..0d6367322 --- /dev/null +++ b/internal/node/mcp_audit_test.go @@ -0,0 +1,510 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package node + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +type safeBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *safeBuffer) Write(p []byte) (n int, err error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *safeBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func (b *safeBuffer) Lines() []string { + b.mu.Lock() + defer b.mu.Unlock() + raw := strings.TrimSpace(b.buf.String()) + if raw == "" { + return nil + } + return strings.Split(raw, "\n") +} + +const testMCPProto = protocol.ID("/test/mcp/audit") + +func setupTestMCPService(t *testing.T, ctx context.Context) (*AgentMeshNode, *AgentMeshNode, *safeBuffer, func()) { + t.Helper() + + var toolCallsCount atomic.Int32 + upstream := httptest.NewServer(mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { + srv := mcp.NewServer(&mcp.Implementation{Name: "upstream", Version: "0.0.1"}, nil) + srv.AddTool(&mcp.Tool{Name: "get_weather", Description: "returns weather", InputSchema: map[string]any{"type": "object"}}, + func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + toolCallsCount.Add(1) + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "sunny in SF"}}}, nil + }) + srv.AddTool(&mcp.Tool{Name: "fail_tool", Description: "returns error result", InputSchema: map[string]any{"type": "object"}}, + func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return &mcp.CallToolResult{ + IsError: true, + Content: []mcp.Content{&mcp.TextContent{Text: "tool failed internally"}}, + }, nil + }) + srv.AddTool(&mcp.Tool{Name: "drop_table", Description: "forbidden tool", InputSchema: map[string]any{"type": "object"}}, + func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "dropped"}}}, nil + }) + return srv + }, nil)) + + nodeA, cleanupA := startBareNode(t, ctx) + nodeB, cleanupB := startBareNode(t, ctx) + + buf := &safeBuffer{} + nodeA.callAuditLogger = audit.New(buf) + + svc := &MCPService{baseService: baseService{ + info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "weather"}, + backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL}, + }} + if err := svc.Init(ctx); err != nil { + t.Fatalf("MCPService.Init: %v", err) + } + nodeA.services.insertService(svc) + + tar := &api.TaskAuthorizationRule{ + Name: "weather-task", + Rules: []*api.TaskRule{{ + AllowedServices: []string{"mcp://weather"}, + Operation: &api.TaskOperation{AllowedTools: []string{"get_weather", "fail_tool"}}, + }}, + } + + nodeA.Host.SetStreamHandler(testMCPProto, func(s network.Stream) { + nodeA.HandleMCPStream(s, RequestContext{ + PeerID: s.Conn().RemotePeer(), + Target: "mcp://weather", + TaskRules: []*api.TaskAuthorizationRule{tar}, + CallerLabels: map[string]string{"env": "prod", "team": "data"}, + }) + }) + + if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil { + t.Fatalf("connect: %v", err) + } + + cleanup := func() { + _ = svc.Teardown() + cleanupB() + cleanupA() + upstream.Close() + } + + return nodeA, nodeB, buf, cleanup +} + +func TestNodeMCPAudit_DisabledByDefault(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + nodeA, nodeB, _, cleanup := setupTestMCPService(t, ctx) + defer cleanup() + + // Explicitly disable audit logging on nodeA. + nodeA.callAuditLogger = nil + + s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProto) + if err != nil { + t.Fatalf("NewStream: %v", err) + } + defer func() { _ = s.Close() }() + + client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "0.0.1"}, nil) + session, err := client.Connect(ctx, NewStreamTransport(s), nil) + if err != nil { + t.Fatalf("client.Connect: %v", err) + } + defer func() { _ = session.Close() }() + + res, err := session.CallTool(ctx, &mcp.CallToolParams{ + Name: "get_weather", + Arguments: map[string]any{"city": "secret_city_name"}, + }) + if err != nil { + t.Fatalf("CallTool failed: %v", err) + } + if len(res.Content) == 0 { + t.Fatal("empty tool content") + } +} + +func TestNodeMCPAudit_InboundSuccess(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + nodeA, nodeB, buf, cleanup := setupTestMCPService(t, ctx) + defer cleanup() + + s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProto) + if err != nil { + t.Fatalf("NewStream: %v", err) + } + defer func() { _ = s.Close() }() + + client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "0.0.1"}, nil) + session, err := client.Connect(ctx, NewStreamTransport(s), nil) + if err != nil { + t.Fatalf("client.Connect: %v", err) + } + defer func() { _ = session.Close() }() + + secretParam := "classified_parameter_value" + res, err := session.CallTool(ctx, &mcp.CallToolParams{ + Name: "get_weather", + Arguments: map[string]any{"city": secretParam}, + }) + if err != nil { + t.Fatalf("CallTool failed: %v", err) + } + if len(res.Content) == 0 { + t.Fatal("empty tool content") + } + + lines := buf.Lines() + if len(lines) != 1 { + t.Fatalf("expected 1 audit log record, got %d: %v", len(lines), lines) + } + + var rec audit.Record + if err := json.Unmarshal([]byte(lines[0]), &rec); err != nil { + t.Fatalf("failed to parse audit record: %v", err) + } + + if rec.CallerPeerID != nodeB.Host.ID().String() { + t.Errorf("CallerPeerID = %q, want %q", rec.CallerPeerID, nodeB.Host.ID().String()) + } + if rec.ProviderPeerID != nodeA.Host.ID().String() { + t.Errorf("ProviderPeerID = %q, want %q", rec.ProviderPeerID, nodeA.Host.ID().String()) + } + if rec.ServiceName != "weather" { + t.Errorf("ServiceName = %q, want %q", rec.ServiceName, "weather") + } + if rec.ToolName != "get_weather" { + t.Errorf("ToolName = %q, want %q", rec.ToolName, "get_weather") + } + if rec.Outcome != audit.OutcomeOK { + t.Errorf("Outcome = %q, want %q", rec.Outcome, audit.OutcomeOK) + } + if rec.CallerLabels["env"] != "prod" || rec.CallerLabels["team"] != "data" { + t.Errorf("CallerLabels = %v, want env=prod, team=data", rec.CallerLabels) + } + if rec.LatencyMS <= 0 { + t.Errorf("LatencyMS = %v, want > 0", rec.LatencyMS) + } + if rec.BytesIn <= 0 { + t.Errorf("BytesIn = %d, want > 0", rec.BytesIn) + } + if rec.BytesOut <= 0 { + t.Errorf("BytesOut = %d, want > 0", rec.BytesOut) + } + if _, err := time.Parse(time.RFC3339Nano, rec.Timestamp); err != nil { + t.Errorf("invalid RFC3339 timestamp %q: %v", rec.Timestamp, err) + } + + // Payload and secret exclusion: Ensure argument values or secrets do not appear. + if strings.Contains(lines[0], secretParam) { + t.Errorf("audit record leaked secret argument payload %q: %s", secretParam, lines[0]) + } + if strings.Contains(lines[0], "sunny in SF") { + t.Errorf("audit record leaked response result payload: %s", lines[0]) + } +} + +func TestNodeMCPAudit_InboundTARDenied(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + nodeA, nodeB, buf, cleanup := setupTestMCPService(t, ctx) + defer cleanup() + + s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProto) + if err != nil { + t.Fatalf("NewStream: %v", err) + } + defer func() { _ = s.Close() }() + + client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "0.0.1"}, nil) + session, err := client.Connect(ctx, NewStreamTransport(s), nil) + if err != nil { + t.Fatalf("client.Connect: %v", err) + } + defer func() { _ = session.Close() }() + + // "drop_table" is not in TAR allowed tools, so it must be denied. + _, err = session.CallTool(ctx, &mcp.CallToolParams{ + Name: "drop_table", + Arguments: map[string]any{}, + }) + if err == nil { + t.Fatal("expected error calling forbidden tool drop_table") + } + + lines := buf.Lines() + if len(lines) != 1 { + t.Fatalf("expected 1 audit log record, got %d: %v", len(lines), lines) + } + + var rec audit.Record + if err := json.Unmarshal([]byte(lines[0]), &rec); err != nil { + t.Fatalf("failed to parse audit record: %v", err) + } + + if rec.ToolName != "drop_table" { + t.Errorf("ToolName = %q, want drop_table", rec.ToolName) + } + if rec.Outcome != audit.OutcomeUnauthorized { + t.Errorf("Outcome = %q, want %q", rec.Outcome, audit.OutcomeUnauthorized) + } + if rec.CallerPeerID != nodeB.Host.ID().String() { + t.Errorf("CallerPeerID = %q, want %q", rec.CallerPeerID, nodeB.Host.ID().String()) + } +} + +func TestNodeMCPAudit_InboundToolError(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + nodeA, nodeB, buf, cleanup := setupTestMCPService(t, ctx) + defer cleanup() + + s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProto) + if err != nil { + t.Fatalf("NewStream: %v", err) + } + defer func() { _ = s.Close() }() + + client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "0.0.1"}, nil) + session, err := client.Connect(ctx, NewStreamTransport(s), nil) + if err != nil { + t.Fatalf("client.Connect: %v", err) + } + defer func() { _ = session.Close() }() + + res, err := session.CallTool(ctx, &mcp.CallToolParams{ + Name: "fail_tool", + Arguments: map[string]any{}, + }) + if err != nil { + t.Fatalf("CallTool returned protocol error: %v", err) + } + if res == nil || !res.IsError { + t.Fatalf("expected IsError: true, got %+v", res) + } + + lines := buf.Lines() + if len(lines) != 1 { + t.Fatalf("expected 1 audit log record, got %d: %v", len(lines), lines) + } + + var rec audit.Record + if err := json.Unmarshal([]byte(lines[0]), &rec); err != nil { + t.Fatalf("failed to parse audit record: %v", err) + } + + if rec.ToolName != "fail_tool" { + t.Errorf("ToolName = %q, want fail_tool", rec.ToolName) + } + if rec.Outcome != audit.OutcomeToolError { + t.Errorf("Outcome = %q, want %q", rec.Outcome, audit.OutcomeToolError) + } +} + +type errWriter struct{} + +func (errWriter) Write(p []byte) (int, error) { + return 0, errors.New("simulated write failure") +} + +func TestNodeMCPAudit_LoggingFailureDoesNotBreakTool(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + nodeA, nodeB, _, cleanup := setupTestMCPService(t, ctx) + defer cleanup() + + // Replace logger with one that always fails on Write. + nodeA.callAuditLogger = audit.New(errWriter{}) + + s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProto) + if err != nil { + t.Fatalf("NewStream: %v", err) + } + defer func() { _ = s.Close() }() + + client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "0.0.1"}, nil) + session, err := client.Connect(ctx, NewStreamTransport(s), nil) + if err != nil { + t.Fatalf("client.Connect: %v", err) + } + defer func() { _ = session.Close() }() + + // Tool call must still succeed. + res, err := session.CallTool(ctx, &mcp.CallToolParams{ + Name: "get_weather", + Arguments: map[string]any{}, + }) + if err != nil { + t.Fatalf("CallTool failed despite audit failure tolerance: %v", err) + } + if len(res.Content) == 0 { + t.Fatal("empty content returned") + } +} + +func TestNodeMCPAudit_ConcurrentEvents(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + nodeA, nodeB, buf, cleanup := setupTestMCPService(t, ctx) + defer cleanup() + + const concurrency = 15 + var wg sync.WaitGroup + errCh := make(chan error, concurrency) + + for i := 0; i < concurrency; i++ { + wg.Add(1) + go func(idx int) { + defer wg.Done() + + s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProto) + if err != nil { + errCh <- fmt.Errorf("stream %d: %w", idx, err) + return + } + defer func() { _ = s.Close() }() + + client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "0.0.1"}, nil) + session, err := client.Connect(ctx, NewStreamTransport(s), nil) + if err != nil { + errCh <- fmt.Errorf("connect %d: %w", idx, err) + return + } + defer func() { _ = session.Close() }() + + _, err = session.CallTool(ctx, &mcp.CallToolParams{ + Name: "get_weather", + Arguments: map[string]any{"i": idx}, + }) + if err != nil { + errCh <- fmt.Errorf("call %d: %w", idx, err) + return + } + }(i) + } + + wg.Wait() + close(errCh) + for err := range errCh { + t.Fatal(err) + } + + lines := buf.Lines() + if len(lines) != concurrency { + t.Fatalf("expected %d audit records, got %d", concurrency, len(lines)) + } + + for i, line := range lines { + var rec audit.Record + if err := json.Unmarshal([]byte(line), &rec); err != nil { + t.Fatalf("line %d invalid json (%s): %v", i, line, err) + } + if rec.ToolName != "get_weather" { + t.Errorf("line %d: ToolName = %q, want get_weather", i, rec.ToolName) + } + if rec.Outcome != audit.OutcomeOK { + t.Errorf("line %d: Outcome = %q, want ok", i, rec.Outcome) + } + } +} + +func TestNodeMCPAudit_OutboundCallMCPTool_Error(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + nodeA, cleanupA := startBareNode(t, ctx) + defer cleanupA() + + buf := &safeBuffer{} + nodeA.callAuditLogger = audit.New(buf) + + // Target a peer with no route / connection, triggering dial failure. + targetPID, _ := peer.Decode("12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN") + _, err := nodeA.CallMCPTool(ctx, targetPID, "mcp://weather/get_forecast", map[string]any{"city": "Tokyo"}, nil) + if err == nil { + t.Fatal("expected CallMCPTool to fail for unconnected peer") + } + + lines := buf.Lines() + if len(lines) != 1 { + t.Fatalf("expected 1 audit record, got %d: %v", len(lines), lines) + } + + var rec audit.Record + if err := json.Unmarshal([]byte(lines[0]), &rec); err != nil { + t.Fatalf("failed to parse audit record: %v", err) + } + + if rec.CallerPeerID != nodeA.Host.ID().String() { + t.Errorf("CallerPeerID = %q, want %q", rec.CallerPeerID, nodeA.Host.ID().String()) + } + if rec.ProviderPeerID != targetPID.String() { + t.Errorf("ProviderPeerID = %q, want %q", rec.ProviderPeerID, targetPID.String()) + } + if rec.ServiceName != "mcp://weather" { + t.Errorf("ServiceName = %q, want mcp://weather", rec.ServiceName) + } + if rec.ToolName != "get_forecast" { + t.Errorf("ToolName = %q, want get_forecast", rec.ToolName) + } + if rec.Outcome != audit.OutcomeCallFailed && rec.Outcome != audit.OutcomeTimeout { + t.Errorf("Outcome = %q, want call_failed or timeout", rec.Outcome) + } + // Verify payload exclusion on outbound call: "Tokyo" must not be in audit record. + if strings.Contains(lines[0], "Tokyo") { + t.Errorf("audit record leaked arguments payload: %s", lines[0]) + } +} diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.go index 4cba40ad6..f2d24171b 100644 --- a/internal/node/mcp_service.go +++ b/internal/node/mcp_service.go @@ -15,7 +15,9 @@ package node import ( + "bytes" "context" + "encoding/json" "errors" "fmt" "os/exec" @@ -25,7 +27,9 @@ import ( "time" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" "github.com/modelcontextprotocol/go-sdk/jsonrpc" "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -50,6 +54,30 @@ type MCPService struct { // (tests) is kept as is. sessionsOnce sync.Once sessions chan struct{} + + auditLogger *audit.Logger + nodeID peer.ID +} + +func (m *MCPService) providerPeerID() string { + if m.nodeID != "" { + return m.nodeID.String() + } + return "unknown" +} + +func (m *MCPService) effectiveAuditLogger(reqCtx RequestContext) *audit.Logger { + if reqCtx.AuditLogger != nil { + return reqCtx.AuditLogger + } + return m.auditLogger +} + +func (m *MCPService) effectiveProviderPeerID(reqCtx RequestContext) string { + if reqCtx.ProviderPeerID != "" { + return reqCtx.ProviderPeerID.String() + } + return m.providerPeerID() } func (m *MCPService) sessionSlots() chan struct{} { @@ -287,6 +315,38 @@ func (m *MCPService) HandleStreamPassThrough(s network.Stream, reqCtx RequestCon clientErrc := make(chan error, 2) backendDone := make(chan struct{}) + auditLogger := m.effectiveAuditLogger(reqCtx) + providerID := m.effectiveProviderPeerID(reqCtx) + + type inFlightCall struct { + toolName string + startTime time.Time + bytesIn int64 + } + var inFlightCalls sync.Map + + defer func() { + if auditLogger != nil { + inFlightCalls.Range(func(key, val any) bool { + call := val.(inFlightCall) + inFlightCalls.Delete(key) + auditLogger.Log(audit.Record{ + Timestamp: call.startTime.UTC().Format(time.RFC3339Nano), + CallerPeerID: reqCtx.PeerID.String(), + CallerLabels: reqCtx.CallerLabels, + ProviderPeerID: providerID, + ServiceName: m.info.GetName(), + ToolName: call.toolName, + Outcome: audit.OutcomeBackendError, + LatencyMS: float64(time.Since(call.startTime).Microseconds()) / 1000.0, + BytesIn: call.bytesIn, + BytesOut: 0, + }) + return true + }) + } + }() + go func() { defer close(backendDone) for { @@ -298,6 +358,45 @@ func (m *MCPService) HandleStreamPassThrough(s network.Stream, reqCtx RequestCon } return } + if auditLogger != nil { + if resp, ok := msg.(*jsonrpc.Response); ok && resp.ID.IsValid() { + respID := fmt.Sprint(resp.ID.Raw()) + if val, found := inFlightCalls.LoadAndDelete(respID); found { + call := val.(inFlightCall) + var bytesOut int64 + if enc, encErr := jsonrpc.EncodeMessage(resp); encErr == nil { + bytesOut = int64(len(enc)) + } + outcome := audit.OutcomeOK + if resp.Error != nil { + var rpcErr *jsonrpc.Error + if errors.As(resp.Error, &rpcErr) { + outcome = audit.ClassifyJSONRPCError(rpcErr.Code) + } else { + outcome = audit.OutcomeCallFailed + } + } else if resp.Result != nil { + if b, mErr := json.Marshal(resp.Result); mErr == nil { + if bytes.Contains(b, []byte(`"isError":true`)) || bytes.Contains(b, []byte(`"isError": true`)) { + outcome = audit.OutcomeToolError + } + } + } + auditLogger.Log(audit.Record{ + Timestamp: call.startTime.UTC().Format(time.RFC3339Nano), + CallerPeerID: reqCtx.PeerID.String(), + CallerLabels: reqCtx.CallerLabels, + ProviderPeerID: providerID, + ServiceName: m.info.GetName(), + ToolName: call.toolName, + Outcome: outcome, + LatencyMS: float64(time.Since(call.startTime).Microseconds()) / 1000.0, + BytesIn: call.bytesIn, + BytesOut: bytesOut, + }) + } + } + } if err := clientConn.Write(ctx, msg); err != nil { logger.Debugf("[MCPService] %s: client write error: %v", m.info.Name, err) clientErrc <- err @@ -314,6 +413,33 @@ func (m *MCPService) HandleStreamPassThrough(s network.Stream, reqCtx RequestCon clientErrc <- err return } + + var isToolCall bool + var isCall bool + var requestID string + var toolName string + var startTime time.Time + var bytesIn int64 + + if req, ok := msg.(*jsonrpc.Request); ok && req.Method == "tools/call" { + isToolCall = true + isCall = req.IsCall() + if req.ID.IsValid() { + requestID = fmt.Sprint(req.ID.Raw()) + } + startTime = time.Now() + if name, nErr := api.MCPToolCallName(req.Params); nErr == nil && name != "" { + toolName = name + } else { + toolName = "unknown" + } + if auditLogger != nil { + if enc, encErr := jsonrpc.EncodeMessage(req); encErr == nil { + bytesIn = int64(len(enc)) + } + } + } + if req, ok := msg.(*jsonrpc.Request); ok && preflightMethodsUnsupportedByPassThrough[req.Method] { resp := &jsonrpc.Response{ID: req.ID, Error: &jsonrpc.Error{Code: jsonrpc.CodeMethodNotFound, Message: req.Method + " is not supported by this pass-through proxy"}} if werr := clientConn.Write(ctx, resp); werr != nil { @@ -335,10 +461,55 @@ func (m *MCPService) HandleStreamPassThrough(s network.Stream, reqCtx RequestCon clientErrc <- werr return } + if isToolCall && auditLogger != nil { + var bytesOut int64 + if enc, encErr := jsonrpc.EncodeMessage(errResp); encErr == nil { + bytesOut = int64(len(enc)) + } + outcome := audit.OutcomeUnauthorized + var rpcErr *jsonrpc.Error + if errors.As(errResp.Error, &rpcErr) { + outcome = audit.ClassifyJSONRPCError(rpcErr.Code) + } + auditLogger.Log(audit.Record{ + Timestamp: startTime.UTC().Format(time.RFC3339Nano), + CallerPeerID: reqCtx.PeerID.String(), + CallerLabels: reqCtx.CallerLabels, + ProviderPeerID: providerID, + ServiceName: m.info.GetName(), + ToolName: toolName, + Outcome: outcome, + LatencyMS: float64(time.Since(startTime).Microseconds()) / 1000.0, + BytesIn: bytesIn, + BytesOut: bytesOut, + }) + } continue } } + if isToolCall && auditLogger != nil && isCall && requestID != "" { + inFlightCalls.Store(requestID, inFlightCall{ + toolName: toolName, + startTime: startTime, + bytesIn: bytesIn, + }) + } if err := backendConn.Write(ctx, msg); err != nil { + if isToolCall && auditLogger != nil && isCall && requestID != "" { + inFlightCalls.Delete(requestID) + auditLogger.Log(audit.Record{ + Timestamp: startTime.UTC().Format(time.RFC3339Nano), + CallerPeerID: reqCtx.PeerID.String(), + CallerLabels: reqCtx.CallerLabels, + ProviderPeerID: providerID, + ServiceName: m.info.GetName(), + ToolName: toolName, + Outcome: audit.OutcomeBackendError, + LatencyMS: float64(time.Since(startTime).Microseconds()) / 1000.0, + BytesIn: bytesIn, + BytesOut: 0, + }) + } logger.Debugf("[MCPService] %s: backend write error: %v", m.info.Name, err) clientErrc <- err return diff --git a/internal/node/middleware.go b/internal/node/middleware.go index c3d0c41a7..cac1c3ed2 100644 --- a/internal/node/middleware.go +++ b/internal/node/middleware.go @@ -24,6 +24,7 @@ import ( "github.com/eclipse-biscuit/biscuit-go/v2" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" "github.com/google/agentmesh/internal/identity" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" @@ -67,6 +68,16 @@ type RequestContext struct { // the caller's Biscuit during stream authentication so downstream stream // handlers (such as MCP pass-through) can enforce tool-level constraints. TaskRules []*api.TaskAuthorizationRule + + // CallerLabels holds the control-plane attested label() facts extracted + // from the caller's verified Biscuit token during stream authentication. + CallerLabels map[string]string + + // ProviderPeerID is the local node's peer ID serving the request. + ProviderPeerID peer.ID + + // AuditLogger is the call audit logger for recording tool call events. + AuditLogger *audit.Logger } // HTTPRequestFacts is what an HTTP request contributes to policy. @@ -173,7 +184,7 @@ func (n *AgentMeshNode) WithBiscuitAuth(next func(network.Stream, RequestContext writer := msgio.NewVarintWriter(ts) - taskRules, err := n.verifyBiscuitTokenWithRules(authFrame.Biscuit, reqCtx) + taskRules, callerLabels, err := n.verifyBiscuitTokenWithRules(authFrame.Biscuit, reqCtx) if err != nil { logger.Warnf("[Auth] AuthZ Denied %s: %v", remotePeer, err) resp := &api.AuthResponse{Success: false, Error: err.Error()} @@ -182,6 +193,7 @@ func (n *AgentMeshNode) WithBiscuitAuth(next func(network.Stream, RequestContext return } reqCtx.TaskRules = taskRules + reqCtx.CallerLabels = callerLabels // Valid. Mutual auth: return our control-plane-minted identity so the // caller can verify this node's attested facts (e.g. region) before @@ -205,18 +217,18 @@ func (n *AgentMeshNode) WithBiscuitAuth(next func(network.Stream, RequestContext // VerifyBiscuitToken checks revocation, cache, and evaluates the token against trusted keys and local policies. func (n *AgentMeshNode) VerifyBiscuitToken(biscuitBytes []byte, reqCtx RequestContext) error { - _, err := n.verifyBiscuitTokenWithRules(biscuitBytes, reqCtx) + _, _, err := n.verifyBiscuitTokenWithRules(biscuitBytes, reqCtx) return err } -func (n *AgentMeshNode) verifyBiscuitTokenWithRules(biscuitBytes []byte, reqCtx RequestContext) ([]*api.TaskAuthorizationRule, error) { +func (n *AgentMeshNode) verifyBiscuitTokenWithRules(biscuitBytes []byte, reqCtx RequestContext) ([]*api.TaskAuthorizationRule, map[string]string, error) { remotePeer := reqCtx.PeerID // Check revocation cache if n.revokedPeers != nil { if _, isRevoked := n.revokedPeers.Get(remotePeer.String()); isRevoked { logger.Warnf("[Auth] Peer %s is revoked", remotePeer) - return nil, fmt.Errorf("peer is revoked") + return nil, nil, fmt.Errorf("peer is revoked") } } @@ -226,12 +238,14 @@ func (n *AgentMeshNode) verifyBiscuitTokenWithRules(biscuitBytes []byte, reqCtx var authorized bool var taskRules []*api.TaskAuthorizationRule + var callerLabels map[string]string var lastErr error for _, pubKey := range keys { logger.Infof("[Auth] Trying key: %x", pubKey.Key) - if rules, err := n.authorizeWithRules(biscuitBytes, reqCtx, pubKey.Key); err == nil { + if rules, labels, err := n.authorizeWithRules(biscuitBytes, reqCtx, pubKey.Key); err == nil { authorized = true taskRules = rules + callerLabels = labels break } else { lastErr = err @@ -243,39 +257,39 @@ func (n *AgentMeshNode) verifyBiscuitTokenWithRules(biscuitBytes []byte, reqCtx if !authorized { if lastErr != nil { - return nil, lastErr + return nil, nil, lastErr } - return nil, fmt.Errorf("authorization failed") + return nil, nil, fmt.Errorf("authorization failed") } - return taskRules, nil + return taskRules, callerLabels, nil } func (n *AgentMeshNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.PublicKey) error { - _, err := n.authorizeWithRules(rawToken, req, pubKey) + _, _, err := n.authorizeWithRules(rawToken, req, pubKey) return err } -func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, pubKey ed25519.PublicKey) ([]*api.TaskAuthorizationRule, error) { +func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, pubKey ed25519.PublicKey) ([]*api.TaskAuthorizationRule, map[string]string, error) { if len(pubKey) != ed25519.PublicKeySize { - return nil, fmt.Errorf("invalid public key size: %d", len(pubKey)) + return nil, nil, fmt.Errorf("invalid public key size: %d", len(pubKey)) } b, taskRules, err := identity.UnmarshalInbound(rawToken) if err != nil { - return nil, fmt.Errorf("invalid biscuit: %w", err) + return nil, nil, fmt.Errorf("invalid biscuit: %w", err) } if n.IsBiscuitRevoked(b) { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", "biscuit is revoked")...) - return nil, fmt.Errorf("biscuit is revoked") + return nil, nil, fmt.Errorf("biscuit is revoked") } authorizer, err := b.Authorizer(pubKey, identity.AuthorizerOptions(n.BiscuitTimeout)...) if err != nil { - return nil, err + return nil, nil, err } if err := identity.RequireAuthorityRequestBinding(b, req.PeerID); err != nil { - return nil, err + return nil, nil, err } // The request as every enforcement point describes it: the service it @@ -307,35 +321,35 @@ func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, pol, err := n.meshPolicy() if err != nil { - return nil, err + return nil, nil, err } if err := identity.AuthorizeMeshRequest(authorizer, meshReq, pol); err != nil { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", err.Error())...) logger.Debugf("Authorizer failure: %v, token: %s", err, b.String()) logger.Debugf("Authorizer state: %s", authorizer.PrintWorld()) - return nil, err + return nil, nil, err } if n.nodeConfig != nil && (n.nodeConfig.RequireTaskScope || n.nodeConfig.MaxTaskTTL > 0) && (!req.Local || req.Protocol == "ext_authz") { if len(taskRules) == 0 { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", "task-scoped credential (tar_block) is required")...) - return nil, fmt.Errorf("task-scoped credential (tar_block) is required") + return nil, nil, fmt.Errorf("task-scoped credential (tar_block) is required") } if n.nodeConfig.MaxTaskTTL > 0 { authExp, expErr := queryExpiration(authorizer) if expErr != nil { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", "missing credential expiration for max_task_ttl check")...) - return nil, fmt.Errorf("credential expiration required for max_task_ttl: %w", expErr) + return nil, nil, fmt.Errorf("credential expiration required for max_task_ttl: %w", expErr) } effectiveExp := api.EffectiveTARExpiration(authExp, taskRules) if effectiveExp.IsZero() { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", "effective credential expiration is zero")...) - return nil, fmt.Errorf("effective credential expiration is zero") + return nil, nil, fmt.Errorf("effective credential expiration is zero") } if remaining := time.Until(effectiveExp); remaining > n.nodeConfig.MaxTaskTTL { reason := fmt.Sprintf("credential remaining lifetime %s exceeds max_task_ttl %s", remaining.Round(time.Second), n.nodeConfig.MaxTaskTTL) logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", reason)...) - return nil, errors.New(reason) + return nil, nil, errors.New(reason) } } } @@ -343,7 +357,7 @@ func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, if len(taskRules) > 0 { if err := api.EvaluateTaskRules(taskRules, meshReq.TaskRequest(), time.Now()); err != nil { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", err.Error())...) - return nil, err + return nil, nil, err } } @@ -396,7 +410,7 @@ func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, if actorPID, pErr := peer.Decode(actorNodeStr); pErr == nil { if _, isRevoked := n.revokedPeers.Get(actorPID.String()); isRevoked { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", "actor_node is revoked")...) - return nil, fmt.Errorf("actor_node %s is revoked", actorPID.String()) + return nil, nil, fmt.Errorf("actor_node %s is revoked", actorPID.String()) } } } @@ -408,12 +422,14 @@ func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, if claims, cErr := queryClaimFacts(authorizer); cErr == nil && len(claims) > 0 { auditFields = append(auditFields, "claims", api.FormatClaims(claims)) } + var callerLabels map[string]string if labels, lErr := queryLabelFacts(authorizer); lErr == nil && len(labels) > 0 { + callerLabels = labels auditFields = append(auditFields, "labels", api.FormatLabels(labels)) } logger.Infow("Audit Traceability", auditFields...) - return taskRules, nil + return taskRules, callerLabels, nil } // auditFields is what every authorization decision logs about the request: diff --git a/internal/node/middleware_test.go b/internal/node/middleware_test.go index 3e468365e..11035fcb5 100644 --- a/internal/node/middleware_test.go +++ b/internal/node/middleware_test.go @@ -1310,7 +1310,7 @@ func TestVerifyBiscuitPreservesPolicyDenialAcrossMultipleTrustedKeys(t *testing. BiscuitTimeout: 500 * time.Millisecond, } - _, err = node.verifyBiscuitTokenWithRules(tokenBytes, RequestContext{ + _, _, err = node.verifyBiscuitTokenWithRules(tokenBytes, RequestContext{ PeerID: callerPeer, Protocol: "/denied/proto", }) diff --git a/internal/node/node.go b/internal/node/node.go index e2042e23a..435d3c12e 100644 --- a/internal/node/node.go +++ b/internal/node/node.go @@ -39,6 +39,7 @@ import ( "github.com/eclipse-biscuit/biscuit-go/v2" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" cpclient "github.com/google/agentmesh/internal/controlplane/client" "github.com/google/agentmesh/internal/identity" "github.com/google/agentmesh/internal/p2plimits" @@ -285,6 +286,9 @@ type AgentMeshNode struct { catalogMCPServer *mcp.Server egressOnce sync.Once egressHandler http.Handler + + callAuditLogger *audit.Logger + callAuditLoggerCloser io.Closer } // SetTokenSource configures the live platform/OIDC token source presented as @@ -532,6 +536,21 @@ func NewAgentMeshNode(cfg Options) (*AgentMeshNode, error) { return nil, fmt.Errorf("failed to create label gate cache: %w", err) } + auditLogPath := cfg.CallAuditLogPath + if auditLogPath == "" && cfg.NodeConfig != nil { + auditLogPath = cfg.NodeConfig.CallAuditLogPath + } + if cfg.CallAuditLogger != nil { + node.callAuditLogger = cfg.CallAuditLogger + } else if auditLogPath != "" { + l, err := audit.NewFromFile(auditLogPath) + if err != nil { + return nil, fmt.Errorf("call audit log: %w", err) + } + node.callAuditLogger = l + node.callAuditLoggerCloser = l + } + return node, nil } @@ -545,6 +564,31 @@ func (n *AgentMeshNode) labels() map[string]string { return n.nodeConfig.Labels } +// ownAttestedLabels returns the node's control-plane attested labels. +func (n *AgentMeshNode) ownAttestedLabels() map[string]string { + if n == nil { + return nil + } + if bBytes := n.GetIdentity(); len(bBytes) > 0 { + if b, err := biscuit.Unmarshal(bBytes); err == nil { + n.keysMu.RLock() + trusted := n.trustedKeys + n.keysMu.RUnlock() + for _, tk := range trusted { + if authorizer, err := b.Authorizer(tk.Key); err == nil { + if labels, err := queryLabelFacts(authorizer); err == nil && len(labels) > 0 { + return labels + } + } + } + } + } + if n.nodeConfig != nil && len(n.nodeConfig.Labels) > 0 { + return n.nodeConfig.Labels + } + return nil +} + // Start initializes the libp2p host, DHT, connects to the routers, and starts runtime components. func (n *AgentMeshNode) Start(ctx context.Context) error { if biscuitBytes := n.GetIdentity(); len(biscuitBytes) > 0 { @@ -2200,6 +2244,14 @@ func (n *AgentMeshNode) RegisterService(ctx context.Context, req *api.RegisterSe if err != nil { return err } + if mcpSvc, isMcp := svc.(*MCPService); isMcp { + if mcpSvc.auditLogger == nil && n.callAuditLogger != nil { + mcpSvc.auditLogger = n.callAuditLogger + } + if mcpSvc.nodeID == "" && n.Host != nil { + mcpSvc.nodeID = n.Host.ID() + } + } return n.services.Register(ctx, svc) } @@ -2231,6 +2283,11 @@ func (n *AgentMeshNode) Teardown() error { n.services.TeardownAll() } var errs []error + if n.callAuditLoggerCloser != nil { + if err := n.callAuditLoggerCloser.Close(); err != nil { + errs = append(errs, err) + } + } if n.Host != nil { if err := n.Host.Close(); err != nil { errs = append(errs, err) diff --git a/internal/node/options.go b/internal/node/options.go index 473e12f89..fe46b615d 100644 --- a/internal/node/options.go +++ b/internal/node/options.go @@ -20,6 +20,7 @@ import ( "time" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" "github.com/google/agentmesh/internal/identity" "github.com/libp2p/go-libp2p/core/crypto" "github.com/multiformats/go-multiaddr" @@ -184,6 +185,12 @@ type Options struct { // OnStreamRefused, when non-nil, is invoked whenever the libp2p auth gate // refuses an unauthenticated or non-router stream. OnStreamRefused func(scope, protocol string) + // CallAuditLogger is the optional sink for tool call audit log records. + // Nil (the default) disables call audit logging unless CallAuditLogPath is set. + CallAuditLogger *audit.Logger + // CallAuditLogPath is the optional file path (or 'stdout'/'stderr'/'-') + // for structured JSONL tool call audit log. Empty (the default) disables audit logging. + CallAuditLogPath string } // Default applies default values to Options if they are not specified. diff --git a/internal/router/config.go b/internal/router/config.go index dceb38de7..8733dcb98 100644 --- a/internal/router/config.go +++ b/internal/router/config.go @@ -22,6 +22,7 @@ import ( "time" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" "github.com/google/agentmesh/internal/identity" "github.com/multiformats/go-multiaddr" ) @@ -145,6 +146,10 @@ type Options struct { // SinglePortBindHost is the configured bind host paired with the bound WS // port when AdvertiseSinglePortIngress is set and IngressURL is empty. SinglePortBindHost string + // CallAuditLogger provides structured JSONL audit logging for calls (e.g. Ingress tool calls). + CallAuditLogger *audit.Logger + // CallAuditLogPath specifies the destination file for call audit logging. + CallAuditLogPath string } // Default sets default values for options. diff --git a/internal/router/ingress.go b/internal/router/ingress.go index 691d43872..120a1635a 100644 --- a/internal/router/ingress.go +++ b/internal/router/ingress.go @@ -34,6 +34,7 @@ import ( "github.com/a2aproject/a2a-go/v2/a2a" "github.com/eclipse-biscuit/biscuit-go/v2" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" "github.com/google/agentmesh/internal/identity" gostream "github.com/libp2p/go-libp2p-gostream" "github.com/libp2p/go-libp2p/core/network" @@ -524,6 +525,20 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request, if _, err := identity.ValidateIngressCallerPreDial(verified, evalParams); err != nil { routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeDeny).Inc() logger.Warnf("[Ingress] Pre-dial AuthZ denied caller (%s) from %s for %s: %v", verified.Principal(), clientIP, targetURI, err) + if r.callAuditLogger != nil && evalParams.MCPTool != "" { + r.callAuditLogger.Log(audit.Record{ + Timestamp: time.Now().UTC().Format(time.RFC3339Nano), + CallerPeerID: ingressCallerPeerID(verified), + CallerLabels: verified.Labels, + ProviderPeerID: targetPeer.String(), + ServiceName: serviceName, + ToolName: evalParams.MCPTool, + Outcome: audit.OutcomeUnauthorized, + LatencyMS: 0, + BytesIn: 0, + BytesOut: 0, + }) + } http.Error(w, "Forbidden", http.StatusForbidden) return } @@ -575,7 +590,7 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request, "method", req.Method, "path", backendPath, ) - r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringPassthrough, "") + r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringPassthrough, "", "", nil) return } @@ -592,6 +607,20 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request, if err != nil { routerIngressRequestsTotal.WithLabelValues(modeStr, ingressOutcomeDeny).Inc() logger.Warnf("[Ingress] Edge AuthZ denied Biscuit caller (%s) from %s for %s: %v", verifiedCaller.Principal(), clientIP, targetURI, err) + if r.callAuditLogger != nil && evalParams.MCPTool != "" { + r.callAuditLogger.Log(audit.Record{ + Timestamp: time.Now().UTC().Format(time.RFC3339Nano), + CallerPeerID: ingressCallerPeerID(verifiedCaller), + CallerLabels: verifiedCaller.Labels, + ProviderPeerID: targetPeer.String(), + ServiceName: serviceName, + ToolName: evalParams.MCPTool, + Outcome: audit.OutcomeUnauthorized, + LatencyMS: 0, + BytesIn: 0, + BytesOut: 0, + }) + } http.Error(w, "Forbidden", http.StatusForbidden) return } @@ -611,7 +640,7 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request, "path", backendPath, ) - r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringEdge, callerBiscuitHdr) + r.forwardIngressHTTP(w, req, transport, targetPeer, serviceTypeStr, serviceName, subpath, hasTrailingOrSubpath, routerBiscuitHeader, api.IngressAuthModeStringEdge, callerBiscuitHdr, evalParams.MCPTool, verifiedCaller) } func (r *Router) forwardIngressHTTP( @@ -622,6 +651,8 @@ func (r *Router) forwardIngressHTTP( serviceTypeStr, serviceName, subpath string, hasTrailingOrSubpath bool, routerBiscuitHeader, modeStr, callerBiscuitHdr string, + mcpTool string, + verifiedCaller *identity.VerifiedBiscuitClaims, ) { upstreamPath := "/" + serviceTypeStr + "/" + serviceName if hasTrailingOrSubpath { @@ -629,6 +660,20 @@ func (r *Router) forwardIngressHTTP( } stripAuth := modeStr == api.IngressAuthModeStringEdge + var start time.Time + var cr *ingressCountingReader + var cw *ingressCountingResponseWriter + shouldAudit := r.callAuditLogger != nil && mcpTool != "" + if shouldAudit { + start = time.Now() + if req.Body != nil { + cr = &ingressCountingReader{ReadCloser: req.Body} + req.Body = cr + } + cw = &ingressCountingResponseWriter{ResponseWriter: w} + w = cw + } + proxy := &httputil.ReverseProxy{ Transport: transport, FlushInterval: -1, @@ -661,6 +706,119 @@ func (r *Router) forwardIngressHTTP( }, } proxy.ServeHTTP(w, req) + + if shouldAudit { + latencyMs := float64(time.Since(start).Microseconds()) / 1000.0 + outcome := audit.OutcomeOK + status := cw.statusCode + if status == 0 { + status = http.StatusOK + } + if status >= 400 { + switch status { + case http.StatusUnauthorized: + outcome = audit.OutcomeUnauthorized + case http.StatusForbidden: + outcome = audit.OutcomeForbidden + case http.StatusNotFound: + outcome = audit.OutcomeNotFound + case http.StatusTooManyRequests: + outcome = audit.OutcomeRateLimited + case http.StatusBadGateway: + outcome = audit.OutcomeBadGateway + case http.StatusGatewayTimeout: + outcome = audit.OutcomeTimeout + default: + if status >= 500 { + outcome = audit.OutcomeBackendError + } else { + outcome = audit.OutcomeCallFailed + } + } + } + + var callerLabels map[string]string + if verifiedCaller != nil { + callerLabels = verifiedCaller.Labels + } + var bytesIn int64 + if cr != nil { + bytesIn = cr.bytesRead + } + r.callAuditLogger.Log(audit.Record{ + Timestamp: start.UTC().Format(time.RFC3339Nano), + CallerPeerID: ingressCallerPeerID(verifiedCaller), + CallerLabels: callerLabels, + ProviderPeerID: targetPeer.String(), + ServiceName: serviceName, + ToolName: mcpTool, + Outcome: outcome, + LatencyMS: latencyMs, + BytesIn: bytesIn, + BytesOut: cw.bytesWritten, + }) + } +} + +type ingressCountingResponseWriter struct { + http.ResponseWriter + statusCode int + bytesWritten int64 +} + +func (w *ingressCountingResponseWriter) WriteHeader(code int) { + w.statusCode = code + w.ResponseWriter.WriteHeader(code) +} + +func (w *ingressCountingResponseWriter) Write(b []byte) (int, error) { + if w.statusCode == 0 { + w.statusCode = http.StatusOK + } + n, err := w.ResponseWriter.Write(b) + w.bytesWritten += int64(n) + return n, err +} + +func (w *ingressCountingResponseWriter) Flush() { + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +type ingressCountingReader struct { + io.ReadCloser + bytesRead int64 +} + +func (r *ingressCountingReader) Read(p []byte) (int, error) { + n, err := r.ReadCloser.Read(p) + r.bytesRead += int64(n) + return n, err +} + +func (r *ingressCountingReader) Close() error { + return r.ReadCloser.Close() +} + +func ingressCallerPeerID(claims *identity.VerifiedBiscuitClaims) string { + if claims == nil { + return "" + } + var raw string + if claims.NodePeerID != "" { + raw = claims.NodePeerID + } else if claims.ActorNodePeerID != "" { + raw = claims.ActorNodePeerID + } else if claims.ClientPeerID != "" { + raw = claims.ClientPeerID + } else { + raw = claims.Principal() + } + if pID, err := peer.Decode(raw); err == nil { + return pID.String() + } + return raw } func (r *Router) serveIngressAgentCard( diff --git a/internal/router/ingress_audit_test.go b/internal/router/ingress_audit_test.go new file mode 100644 index 000000000..6b8448514 --- /dev/null +++ b/internal/router/ingress_audit_test.go @@ -0,0 +1,420 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package router + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" + "github.com/google/agentmesh/internal/identity" + gostream "github.com/libp2p/go-libp2p-gostream" + "github.com/libp2p/go-libp2p/core/host" +) + +type routerAuditBuffer struct { + mu sync.Mutex + buf bytes.Buffer + notify chan struct{} +} + +func newRouterAuditBuffer() *routerAuditBuffer { + return &routerAuditBuffer{ + notify: make(chan struct{}, 100), + } +} + +func (b *routerAuditBuffer) Write(p []byte) (n int, err error) { + b.mu.Lock() + n, err = b.buf.Write(p) + b.mu.Unlock() + if b.notify != nil { + select { + case b.notify <- struct{}{}: + default: + } + } + return n, err +} + +func (b *routerAuditBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func (b *routerAuditBuffer) Lines() []string { + b.mu.Lock() + defer b.mu.Unlock() + raw := strings.TrimSpace(b.buf.String()) + if raw == "" { + return nil + } + return strings.Split(raw, "\n") +} + +func (b *routerAuditBuffer) WaitForLines(count int, timeout time.Duration) []string { + deadline := time.Now().Add(timeout) + for { + if lines := b.Lines(); len(lines) >= count { + return lines + } + remaining := time.Until(deadline) + if remaining <= 0 { + return b.Lines() + } + select { + case <-b.notify: + case <-time.After(remaining): + return b.Lines() + } + } +} + +type routerErrWriter struct{} + +func (e *routerErrWriter) Write(_ []byte) (int, error) { + return 0, errors.New("simulated disk full") +} + +func setupIngressAuditRouter(t *testing.T, auditLogger *audit.Logger) (*Router, host.Host, ed25519.PrivateKey, []*api.PolicyRole) { + t.Helper() + + cpPub, cpPriv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("GenerateKey: %v", err) + } + + r := newDirectoryRouter(t) + r.config.ControlPlaneURL = "https://hub.example.com" + r.config.BiscuitTimeout = 2 * time.Second + r.callAuditLogger = auditLogger + + routerBiscuitRaw, err := identity.MintBootstrapBiscuitToken(cpPriv, r.Host.ID(), api.RoleRouter, time.Now().Add(time.Hour), []*api.PolicyRole{ + {Name: api.RoleRouter, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}}, + }, nil) + if err != nil { + t.Fatalf("MintBootstrapBiscuitToken(router): %v", err) + } + r.keysMu.Lock() + r.trustedPublicKeys = []ed25519.PublicKey{cpPub} + r.credential = credential{biscuit: routerBiscuitRaw, expiration: time.Now().Add(time.Hour)} + r.keysMu.Unlock() + + providerRole := &api.PolicyRole{ + Name: "agent-host", + AllowedPublish: []string{"mcp://*"}, + AllowedIngress: []*api.IngressGrant{ + { + Services: []string{"mcp://calc"}, + }, + }, + } + callerRole := &api.PolicyRole{ + Name: "caller", + AllowedServices: []string{"mcp://calc"}, + AllowedTargets: []string{"*"}, + } + roles := []*api.PolicyRole{providerRole, callerRole} + bindings := []*api.PolicyBinding{ + {Role: "caller", Members: []string{"email:alice@example.com"}}, + } + compiled, warnings := api.BuildPolicyRules(roles, bindings) + if len(warnings) != 0 { + t.Fatalf("BuildPolicyRules warnings: %v", warnings) + } + meshRules, err := api.ParseDatalogRules(api.PolicyRuleTexts(compiled)) + if err != nil { + t.Fatalf("ParseDatalogRules: %v", err) + } + r.policy.Store(&meshPolicy{rules: meshRules}) + + provider := attachWithRole(t, r, cpPub, cpPriv, providerRole) + providerAddr := provider.Addrs()[0].String() + "/p2p/" + provider.ID().String() + + ingListener, err := gostream.Listen(provider, api.IngressProtocolID) + if err != nil { + t.Fatalf("gostream.Listen: %v", err) + } + t.Cleanup(func() { _ = ingListener.Close() }) + + upstreamMux := http.NewServeMux() + upstreamMux.HandleFunc("/mcp/calc", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"sum":3}}`)) + }) + upstreamSrv := &http.Server{Handler: upstreamMux, ReadHeaderTimeout: 5 * time.Second} + go func() { _ = upstreamSrv.Serve(ingListener) }() + t.Cleanup(func() { _ = upstreamSrv.Close() }) + + key, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_MCP, "calc") + if err != nil { + t.Fatal(err) + } + resp := ask(t, provider, r.Host.ID(), provideWithIngress(key, "mcp://calc", &api.ServiceIngress{ + AuthMode: api.IngressAuthMode_INGRESS_AUTH_MODE_EDGE, + }, providerAddr)) + if resp.GetError() != "" { + t.Fatalf("provide mcp://calc failed: %s", resp.GetError()) + } + + if err := r.serveIngress("127.0.0.1:0"); err != nil { + t.Fatalf("serveIngress: %v", err) + } + t.Cleanup(func() { + if r.ingressServer != nil { + _ = r.ingressServer.Close() + } + }) + r.isReady.Store(true) + + return r, provider, cpPriv, roles +} + +func mintTestCallerToken(t *testing.T, cpPriv ed25519.PrivateKey, provider host.Host, roles []*api.PolicyRole, labels map[string]string, allowedTools []string) string { + t.Helper() + + var taskRule *api.TaskAuthorizationRule + if len(allowedTools) > 0 { + taskRule = &api.TaskAuthorizationRule{ + Name: "calc-task", + Rules: []*api.TaskRule{ + { + AllowedServices: []string{"mcp://calc"}, + Operation: &api.TaskOperation{AllowedTools: allowedTools}, + }, + }, + } + } + + claims := jwt.MapClaims{ + "sub": "alice", + "email": "alice@example.com", + } + + tok, _, err := identity.MintBiscuitToken(cpPriv, claims, nil, provider.ID(), time.Now().Add(time.Hour), []string{"caller"}, roles, labels) + if err != nil { + t.Fatalf("MintBiscuitToken: %v", err) + } + if taskRule != nil { + tok, err = identity.AttenuateBiscuit(tok, taskRule) + if err != nil { + t.Fatalf("AttenuateBiscuit: %v", err) + } + } + tok, err = identity.SealBiscuit(tok) + if err != nil { + t.Fatalf("SealBiscuit: %v", err) + } + return base64.StdEncoding.EncodeToString(tok) +} + +func TestRouterIngressAudit_DisabledByDefault(t *testing.T) { + r, provider, cpPriv, roles := setupIngressAuditRouter(t, nil) + client := &http.Client{Timeout: 5 * time.Second} + baseURL := "http://" + r.IngressAddr().String() + "/ingress" + + tok := mintTestCallerToken(t, cpPriv, provider, roles, nil, []string{"add"}) + + req, err := http.NewRequest(http.MethodPost, baseURL+"/"+provider.ID().String()+"/mcp/calc", + strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add","arguments":{"a":1,"b":2}}}`)) + if err != nil { + t.Fatalf("http.NewRequest: %v", err) + } + req.Header.Set("Authorization", "Bearer "+tok) + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("client.Do: %v", err) + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200", resp.StatusCode) + } + + if r.CallAuditLogger() != nil { + t.Errorf("expected CallAuditLogger() to be nil when disabled") + } +} + +func TestRouterIngressAudit_SuccessAndPayloadExclusion(t *testing.T) { + buf := newRouterAuditBuffer() + logger := audit.New(buf) + + r, provider, cpPriv, roles := setupIngressAuditRouter(t, logger) + client := &http.Client{Timeout: 5 * time.Second} + baseURL := "http://" + r.IngressAddr().String() + "/ingress" + + labels := map[string]string{"env": "prod", "tier": "gold"} + tok := mintTestCallerToken(t, cpPriv, provider, roles, labels, []string{"add"}) + + secretPayload := "super_secret_payload_argument_value" + bodyStr := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add","arguments":{"a":1,"b":2,"secret":"` + secretPayload + `"}}}` + + req, err := http.NewRequest(http.MethodPost, baseURL+"/"+provider.ID().String()+"/mcp/calc", strings.NewReader(bodyStr)) + if err != nil { + t.Fatalf("http.NewRequest: %v", err) + } + req.Header.Set("Authorization", "Bearer "+tok) + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("client.Do: %v", err) + } + _, _ = io.ReadAll(resp.Body) + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200", resp.StatusCode) + } + + lines := buf.WaitForLines(1, 2*time.Second) + if len(lines) != 1 { + t.Fatalf("expected 1 audit record, got %d: %v", len(lines), lines) + } + + var rec audit.Record + if err := json.Unmarshal([]byte(lines[0]), &rec); err != nil { + t.Fatalf("json.Unmarshal audit record: %v", err) + } + + if rec.ProviderPeerID != provider.ID().String() { + t.Errorf("ProviderPeerID = %q, want %q", rec.ProviderPeerID, provider.ID().String()) + } + if rec.ServiceName != "calc" { + t.Errorf("ServiceName = %q, want %q", rec.ServiceName, "calc") + } + if rec.ToolName != "add" { + t.Errorf("ToolName = %q, want %q", rec.ToolName, "add") + } + if rec.Outcome != audit.OutcomeOK { + t.Errorf("Outcome = %q, want %q", rec.Outcome, audit.OutcomeOK) + } + if rec.CallerLabels["env"] != "prod" || rec.CallerLabels["tier"] != "gold" { + t.Errorf("CallerLabels = %v, want env=prod, tier=gold", rec.CallerLabels) + } + if rec.Timestamp == "" { + t.Errorf("Timestamp is empty") + } else if _, err := time.Parse(time.RFC3339Nano, rec.Timestamp); err != nil { + t.Errorf("Timestamp %q is not RFC3339: %v", rec.Timestamp, err) + } + if rec.BytesIn <= 0 { + t.Errorf("BytesIn = %d, want > 0", rec.BytesIn) + } + if rec.BytesOut <= 0 { + t.Errorf("BytesOut = %d, want > 0", rec.BytesOut) + } + + logOutput := buf.String() + if strings.Contains(logOutput, secretPayload) { + t.Errorf("SECURITY LEAK: audit log contains sensitive payload: %s", logOutput) + } + if strings.Contains(logOutput, tok) { + t.Errorf("SECURITY LEAK: audit log contains bearer token: %s", logOutput) + } +} + +func TestRouterIngressAudit_PreDialTARRejection(t *testing.T) { + buf := newRouterAuditBuffer() + logger := audit.New(buf) + + r, provider, cpPriv, roles := setupIngressAuditRouter(t, logger) + client := &http.Client{Timeout: 5 * time.Second} + baseURL := "http://" + r.IngressAddr().String() + "/ingress" + + // Token only allows "add", so "drop_database" is denied pre-dial. + tok := mintTestCallerToken(t, cpPriv, provider, roles, map[string]string{"env": "test"}, []string{"add"}) + + req, err := http.NewRequest(http.MethodPost, baseURL+"/"+provider.ID().String()+"/mcp/calc", + strings.NewReader(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"drop_database"}}`)) + if err != nil { + t.Fatalf("http.NewRequest: %v", err) + } + req.Header.Set("Authorization", "Bearer "+tok) + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("client.Do: %v", err) + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusForbidden { + t.Fatalf("status = %d, want 403 Forbidden", resp.StatusCode) + } + + lines := buf.Lines() + if len(lines) != 1 { + t.Fatalf("expected 1 audit record, got %d: %v", len(lines), lines) + } + + var rec audit.Record + if err := json.Unmarshal([]byte(lines[0]), &rec); err != nil { + t.Fatalf("json.Unmarshal: %v", err) + } + + if rec.ToolName != "drop_database" { + t.Errorf("ToolName = %q, want drop_database", rec.ToolName) + } + if rec.Outcome != audit.OutcomeUnauthorized { + t.Errorf("Outcome = %q, want %q", rec.Outcome, audit.OutcomeUnauthorized) + } + if rec.ServiceName != "calc" { + t.Errorf("ServiceName = %q, want calc", rec.ServiceName) + } + if rec.CallerLabels["env"] != "test" { + t.Errorf("CallerLabels = %v, want env=test", rec.CallerLabels) + } +} + +func TestRouterIngressAudit_LoggingFailureTolerance(t *testing.T) { + logger := audit.New(&routerErrWriter{}) + + r, provider, cpPriv, roles := setupIngressAuditRouter(t, logger) + client := &http.Client{Timeout: 5 * time.Second} + baseURL := "http://" + r.IngressAddr().String() + "/ingress" + + tok := mintTestCallerToken(t, cpPriv, provider, roles, nil, []string{"add"}) + + req, err := http.NewRequest(http.MethodPost, baseURL+"/"+provider.ID().String()+"/mcp/calc", + strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add","arguments":{"a":1,"b":2}}}`)) + if err != nil { + t.Fatalf("http.NewRequest: %v", err) + } + req.Header.Set("Authorization", "Bearer "+tok) + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("client.Do: %v", err) + } + defer func() { _ = resp.Body.Close() }() + + // Even though audit logger write fails, the ingress tool call must succeed! + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200 OK despite logger failure", resp.StatusCode) + } +} diff --git a/internal/router/router.go b/internal/router/router.go index 489475032..621599d7b 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -37,6 +37,7 @@ import ( "github.com/eclipse-biscuit/biscuit-go/v2" "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/audit" cpclient "github.com/google/agentmesh/internal/controlplane/client" "github.com/google/agentmesh/internal/identity" "github.com/google/agentmesh/internal/p2plimits" @@ -384,6 +385,8 @@ type Router struct { // since the last one that answered. externalAddrLookupFailures atomic.Int32 authFailureLog perPeerLogLimiter + + callAuditLogger *audit.Logger } // NewRouter initializes the router. @@ -395,13 +398,31 @@ func NewRouter(ctx context.Context, config Options) (*Router, error) { ctx, cancel := context.WithCancel(ctx) + var auditLogger *audit.Logger + if config.CallAuditLogger != nil { + auditLogger = config.CallAuditLogger + } else if config.CallAuditLogPath != "" { + l, err := audit.NewFromFile(config.CallAuditLogPath) + if err != nil { + cancel() + return nil, fmt.Errorf("failed to open call audit log: %w", err) + } + auditLogger = l + } + handshakeLimiter, err := ratelimit.NewPeerRateLimiter(handshakeLimiterSize) if err != nil { + if auditLogger != nil { + _ = auditLogger.Close() + } cancel() return nil, fmt.Errorf("failed to create handshake rate limiter: %w", err) } ingressLimiter, err := ratelimit.NewPeerRateLimiterWithRate(handshakeLimiterSize, ingressRateLimitPerIP, ingressRateBurstPerIP) if err != nil { + if auditLogger != nil { + _ = auditLogger.Close() + } cancel() return nil, fmt.Errorf("failed to create ingress rate limiter: %w", err) } @@ -413,6 +434,7 @@ func NewRouter(ctx context.Context, config Options) (*Router, error) { handshakeLimiter: handshakeLimiter, ingressLimiter: ingressLimiter, syncTrigger: make(chan struct{}, 1), + callAuditLogger: auditLogger, }, nil } @@ -2017,10 +2039,20 @@ func (r *Router) Close() error { errs = append(errs, err) } } + if r.callAuditLogger != nil { + if err := r.callAuditLogger.Close(); err != nil { + errs = append(errs, err) + } + } r.wg.Wait() return errors.Join(errs...) } +// CallAuditLogger returns the configured call audit logger, if any. +func (r *Router) CallAuditLogger() *audit.Logger { + return r.callAuditLogger +} + func getOrGeneratePeerKey(keyPath string) (crypto.PrivKey, error) { if err := os.MkdirAll(filepath.Dir(keyPath), 0755); err != nil { return nil, err