Skip to content

feat: add optional metadata-only call audit logging - #980

Open
roonakyadav wants to merge 2 commits into
google:mainfrom
roonakyadav:feat/optional-call-audit-log
Open

roonakyadav wants to merge 2 commits into
google:mainfrom
roonakyadav:feat/optional-call-audit-log

Conversation

@roonakyadav

Copy link
Copy Markdown
Contributor

Summary

Adds an optional, operator-configurable tool call audit logging mechanism on nodes and edge routers, capturing tool call metadata as structured JSONL while strictly excluding arguments, prompts, results, response bodies, and credentials.

Closes #974


Architecture & Call Boundaries

Tool calls in Agent Mesh occur across distinct boundaries. Call audit logging is implemented at the critical call boundaries where identity, authorization, and byte transfer are verified:

  1. Provider Node Inbound libp2p MCP Streams (internal/node/mcp_service.go):

    • Captures inbound tools/call requests over the mesh protocol (/mcp/1.0.0 libp2p streams).
    • Audits pre-execution authorization failures (e.g. Task Authorization Rule denials).
    • Audits completed tool executions upon receiving responses from the local MCP backend, measuring total execution latency, bytes received, and bytes emitted.
    • Extracts caller identity and control-plane attested labels directly from authenticated request context (RequestContext.CallerLabels from Biscuit query facts), never arbitrary caller headers.
  2. Caller Node Outbound Tool Invocations (internal/node/mcp.go):

    • Captures outbound CallMCPTool invocations made by the node to remote mesh peers.
    • Audits connection setup failures, label mismatches, unauthorized rejections, timeouts, and successful tool responses.
  3. Router Edge HTTP Ingress (internal/router/ingress.go):

    • Captures external HTTP/JSON-RPC MCP tool calls terminating at the router's /ingress/ edge gateway.
    • Audits pre-dial Task Authorization Rule rejections and unauthorized edge denials (OutcomeUnauthorized).
    • Audits proxied MCP tool calls via counting response writer and request body streams (OutcomeOK, OutcomeForbidden, OutcomeBadGateway, OutcomeTimeout, etc.).
    • Attributes authenticated caller peer ID and attested labels from verified Biscuit claims (VerifiedBiscuitClaims.Labels).

Deliberate Scope Limitations & Zero-Trust Encrypted Relays

  • Transit Circuit Relay: libp2p Circuit Relay v2 routers relay end-to-end encrypted Noise/TLS transport streams between mesh nodes. In accordance with Agent Mesh's Zero-Trust architecture, relay routers cannot inspect or decrypt relayed payload frames without violating confidentiality and breaking end-to-end encryption. Therefore, transit relay traffic is not decrypted for call audit logging; tool call audit logging operates at the termination endpoints (the provider node, caller node, or edge ingress termination point).

Captured Metadata (Metadata Only)

Each audit record is emitted as a single, atomic JSONL line with the following fields:

  • timestamp: UTC instant formatted in RFC 3339 nano (2026-11-28T...Z).
  • caller_peer_id: Authenticated libp2p peer ID of the caller (or verified Biscuit principal).
  • caller_labels: Control-plane attested key-value label facts (map[string]string), omitted if none.
  • provider_peer_id: Peer ID of the serving node.
  • service_name: Fully qualified or registered service name (e.g., calc, mcp://calc).
  • tool_name: Invoked MCP tool name.
  • outcome: Safe, standardized outcome classification (ok, unauthorized, invalid_params, not_found, timeout, cancelled, rate_limited, tool_error, backend_error, bad_gateway, forbidden, call_failed, labels_not_satisfied, provider_not_granted).
  • latency_ms: Measured round-trip latency in milliseconds (float64).
  • bytes_in: Count of request payload bytes transferred into the boundary.
  • bytes_out: Count of response payload bytes emitted from the boundary.

Privacy & Zero-Leak Guarantees

  • Payload Exclusion: Request arguments, prompt text, response content, output data, JSON-RPC parameter values, and raw payloads are NEVER captured or serialized into audit records.
  • Credential Exclusion: Bearer tokens, Biscuit tokens, JWTs, proof-of-possession challenges, and authorization headers are never logged.
  • Safe Outcome Classification: Raw backend error messages and exception stack traces are never recorded; instead, errors are mapped to safe outcome class identifiers (OutcomeUnauthorized, OutcomeBackendError, OutcomeToolError, etc.) to prevent data leaks.
  • Trusted Identities: Caller identities and labels are sourced exclusively from cryptographically verified Biscuit authority facts or libp2p authenticated connection security handshakes, never untrusted caller HTTP headers.

Operator Configuration

Disabled by default (zero overhead and zero allocations when disabled):

  • CLI Flag (agentmesh-node, agentmesh-router):
    --call-audit-log-path=/var/log/agentmesh/call-audit.jsonl
    # Or output to standard streams:
    --call-audit-log-path=stdout
    --call-audit-log-path=stderr
  • Environment Variable:
    export AGENTMESH_CALL_AUDIT_LOG_PATH=/var/log/agentmesh/call-audit.jsonl
  • Node Configuration File (agentmesh-node.yaml):
    audit:
      call_log_path: /var/log/agentmesh/call-audit.jsonl

Reliability & Concurrency Guarantees

  • Execution Isolation: Audit logging failures (such as a full disk or closed sink) are caught and swallowed, ensuring tool execution is never broken by logging issues.
  • Thread Safety: All writes to the underlying sink are synchronized via mutex and written as atomic single-line JSON records.
  • Concurrent Call Isolation: In-flight calls across multiplexed libp2p streams and concurrent HTTP reverse proxy requests are tracked independently using request-correlated contexts and local response wrappers.

Testing

Added comprehensive unit and integration tests covering:

  1. internal/audit/audit_test.go:
    • Disabled by default (nil safety, zero allocations).
    • Atomic JSONL formatting and payload/credential exclusion validation.
    • High concurrency safety across 50 concurrent goroutines writing simultaneously.
    • Failure tolerance against write errors (errWriter).
    • JSON-RPC error code classification.
    • File creation, permissions (0600), and auto-populated RFC 3339 timestamps.
  2. internal/node/mcp_audit_test.go:
    • Verification that audit logging is disabled by default.
    • Inbound tool call success metadata attribution (caller peer ID, provider peer ID, service, tool, latency, byte counts).
    • Inbound Task Authorization Rule denial (OutcomeUnauthorized).
    • Inbound tool error reporting without leaking backend error strings.
    • Logging failure tolerance during live stream execution.
    • Concurrent multiplexed stream audit events (15 concurrent streams tested under -race).
    • Outbound CallMCPTool error classification and payload exclusion.
  3. internal/router/ingress_audit_test.go:
    • Router ingress audit logging disabled by default.
    • Ingress tool call success with verified caller peer ID and attested label attribution.
    • Ingress pre-dial Task Authorization Rule rejection.
    • Ingress logging failure tolerance without impacting HTTP reverse proxy execution.

@roonakyadav
roonakyadav requested a review from aojea as a code owner November 28, 2026 14:13

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces structured call audit logging (JSONL) for tool invocations across mesh nodes and routers, capturing metadata while strictly excluding payloads and secrets. It adds a new internal/audit package, configures CLI and environment variables for the log path, and integrates logging into MCP tool calls, pass-through services, and router ingress. Feedback on the changes highlights a security-critical requirement to canonicalize raw peer IDs at the boundary using peer.Decode in ingressCallerPeerID, and suggests leveraging the audit.ClassifyJSONRPCError helper in MCPService to improve consistency and maintainability.

Comment on lines +804 to 818
func ingressCallerPeerID(claims *identity.VerifiedBiscuitClaims) string {
if claims == nil {
return ""
}
if claims.NodePeerID != "" {
return claims.NodePeerID
}
if claims.ActorNodePeerID != "" {
return claims.ActorNodePeerID
}
if claims.ClientPeerID != "" {
return claims.ClientPeerID
}
return claims.Principal()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Section 1: Peer IDs must be canonicalized at the boundary

The peer ID strings extracted from the verified Biscuit claims (claims.NodePeerID, claims.ActorNodePeerID, claims.ClientPeerID, or claims.Principal()) are raw, untrusted wire inputs and may not be in the canonical base58 multihash form. Storing or logging non-canonical peer IDs violates the canonicalization boundary rule and can cause bans, admission, or correlation checks to silently miss.

Please decode the raw peer ID string using peer.Decode to canonicalize it before returning.

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
}
References
  1. Peer IDs must be canonicalized at the boundary. A raw string copied off the wire and used as a key or stored in a record is a different key for the same peer, and a ban, admission or dedup check silently misses. (link)

Comment on lines +469 to +473
outcome := audit.OutcomeUnauthorized
var rpcErr *jsonrpc.Error
if errors.As(errResp.Error, &rpcErr) && rpcErr.Code == jsonrpc.CodeInvalidParams {
outcome = audit.OutcomeInvalidParams
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of hardcoding the check for jsonrpc.CodeInvalidParams, leverage the audit.ClassifyJSONRPCError helper function to map the JSON-RPC error code to its standardized outcome class. This improves consistency and maintainability.

Suggested change
outcome := audit.OutcomeUnauthorized
var rpcErr *jsonrpc.Error
if errors.As(errResp.Error, &rpcErr) && rpcErr.Code == jsonrpc.CodeInvalidParams {
outcome = audit.OutcomeInvalidParams
}
outcome := audit.OutcomeUnauthorized
var rpcErr *jsonrpc.Error
if errors.As(errResp.Error, &rpcErr) {
outcome = audit.ClassifyJSONRPCError(rpcErr.Code)
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optional call audit log (metadata only) on nodes/routers

1 participant