Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions api/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions cmd/agentmesh-node/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ var (
secretsDirFlag string
controlPlaneSyncIntervalFlag time.Duration
cloudProviderFlag string
callAuditLogPathFlag string
)

var logger = golog.Logger("agentmesh-node-cli")
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -468,6 +472,7 @@ func main() {
DiscoveryConcurrency: discoveryConcurrencyFlag,
BackendProbeTimeout: backendProbeTimeoutFlag,
SecretsDir: secretsDirFlag,
CallAuditLogPath: callAuditLogPathFlag,
}
}

Expand Down Expand Up @@ -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")
Expand Down
7 changes: 7 additions & 0 deletions cmd/agentmesh-router/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ var (
ingressTLSKeyPath string
allowInsecureIngressHTTP bool
publicControlPlaneURL string
callAuditLogPath string
)

var logger = golog.Logger("agentmesh-router-cli")
Expand All @@ -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,
Expand Down Expand Up @@ -122,6 +127,7 @@ func main() {
IngressTLSKeyPath: ingressTLSKeyPath,
AllowInsecureIngressHTTP: allowInsecureIngressHTTP,
PublicControlPlaneURL: publicControlPlaneURL,
CallAuditLogPath: callAuditLogPath,
}
labels, err := api.ParseLabelFlags(labelFlags)
if err != nil {
Expand Down Expand Up @@ -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()
Expand Down
176 changes: 176 additions & 0 deletions internal/audit/audit.go
Original file line number Diff line number Diff line change
@@ -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
}
}
Loading
Loading