Documentation
¶
Overview ¶
Package audit provides audit logging functionality for ToolHive.
Package audit provides audit logging configuration for ToolHive.
Package audit provides audit logging configuration for ToolHive.
+groupName=toolhive.stacklok.dev +versionName=audit
Package audit provides audit logging functionality for ToolHive. This package includes audit event structures and utilities based on the auditevent library from metal-toolbox/auditevent to ensure NIST SP 800-53 compliance.
Package audit provides MCP-specific audit event types and constants.
Package audit provides audit logging functionality for ToolHive.
Index ¶
- Constants
- func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
- func GetMiddlewareFromFile(path string, transportType string) (func(http.Handler) http.Handler, error)
- func NewAuditLogger(w io.Writer) *slog.Logger
- func WithBackendInfo(ctx context.Context, info *BackendInfo) context.Context
- type AuditEvent
- type Auditor
- type BackendInfo
- type Config
- func (c *Config) CreateMiddlewareWithTransport(transportType string) (types.MiddlewareFunction, error)
- func (in *Config) DeepCopy() *Config
- func (in *Config) DeepCopyInto(out *Config)
- func (c *Config) GetLogWriter() (io.Writer, error)
- func (c *Config) ShouldAuditEvent(eventType string) bool
- func (c *Config) Validate() error
- type EventMetadata
- type EventSource
- type Middleware
- type MiddlewareParams
- type WorkflowAuditor
- func (w *WorkflowAuditor) LogStepCompleted(ctx context.Context, workflowID string, stepID string, duration time.Duration, ...)
- func (w *WorkflowAuditor) LogStepFailed(ctx context.Context, workflowID string, stepID string, duration time.Duration, ...)
- func (w *WorkflowAuditor) LogStepSkipped(ctx context.Context, workflowID string, stepID string, condition string)
- func (w *WorkflowAuditor) LogStepStarted(ctx context.Context, workflowID string, stepID string, stepType string, ...)
- func (w *WorkflowAuditor) LogWorkflowCompleted(ctx context.Context, workflowID string, workflowName string, ...)
- func (w *WorkflowAuditor) LogWorkflowFailed(ctx context.Context, workflowID string, workflowName string, ...)
- func (w *WorkflowAuditor) LogWorkflowStarted(ctx context.Context, workflowID string, workflowName string, ...)
- func (w *WorkflowAuditor) LogWorkflowTimedOut(ctx context.Context, workflowID string, workflowName string, ...)
Constants ¶
const ( // OutcomeSuccess indicates the event was successful OutcomeSuccess = "success" // OutcomeFailure indicates the event failed OutcomeFailure = "failure" // OutcomeError indicates the event resulted in an error OutcomeError = "error" // OutcomeDenied indicates the event was denied (e.g., by authorization) OutcomeDenied = "denied" )
Common event outcomes
const ( // SourceTypeNetwork indicates the event came from a network request SourceTypeNetwork = "network" // SourceTypeLocal indicates the event came from a local source SourceTypeLocal = "local" )
Common source types
const ( // EventTypeMCPInitialize represents an MCP initialization event EventTypeMCPInitialize = "mcp_initialize" // EventTypeSSEConnection represents an SSE connection event EventTypeSSEConnection = "sse_connection" // EventTypeMCPToolCall represents an MCP tool call event EventTypeMCPToolCall = "mcp_tool_call" // EventTypeMCPToolsList represents an MCP tools list event EventTypeMCPToolsList = "mcp_tools_list" // EventTypeMCPResourceRead represents an MCP resource read event EventTypeMCPResourceRead = "mcp_resource_read" // EventTypeMCPResourcesList represents an MCP resources list event EventTypeMCPResourcesList = "mcp_resources_list" // EventTypeMCPPromptGet represents an MCP prompt get event EventTypeMCPPromptGet = "mcp_prompt_get" // EventTypeMCPPromptsList represents an MCP prompts list event EventTypeMCPPromptsList = "mcp_prompts_list" // EventTypeMCPNotification represents an MCP notification event EventTypeMCPNotification = "mcp_notification" // EventTypeMCPPing represents an MCP ping event EventTypeMCPPing = "mcp_ping" // EventTypeMCPLogging represents an MCP logging event EventTypeMCPLogging = "mcp_logging" // EventTypeMCPCompletion represents an MCP completion event EventTypeMCPCompletion = "mcp_completion" // EventTypeMCPRootsListChanged represents an MCP roots list changed notification EventTypeMCPRootsListChanged = "mcp_roots_list_changed" // Workflow-specific event types for vMCP composite workflow execution // EventTypeWorkflowStarted represents workflow execution start EventTypeWorkflowStarted = "vmcp_workflow_started" // EventTypeWorkflowCompleted represents successful workflow completion EventTypeWorkflowCompleted = "vmcp_workflow_completed" // EventTypeWorkflowFailed represents workflow failure EventTypeWorkflowFailed = "vmcp_workflow_failed" // EventTypeWorkflowTimedOut represents workflow timeout EventTypeWorkflowTimedOut = "vmcp_workflow_timed_out" // EventTypeWorkflowStepStarted represents workflow step execution start EventTypeWorkflowStepStarted = "vmcp_workflow_step_started" // EventTypeWorkflowStepCompleted represents successful step completion EventTypeWorkflowStepCompleted = "vmcp_workflow_step_completed" // EventTypeWorkflowStepFailed represents step failure EventTypeWorkflowStepFailed = "vmcp_workflow_step_failed" // EventTypeWorkflowStepSkipped represents conditional step skip EventTypeWorkflowStepSkipped = "vmcp_workflow_step_skipped" // Fallback event types for unrecognized or generic requests // EventTypeMCPRequest represents a generic MCP request when specific type cannot be determined EventTypeMCPRequest = "mcp_request" // EventTypeHTTPRequest represents a generic HTTP request (non-MCP) EventTypeHTTPRequest = "http_request" )
MCP-specific event types based on the Model Context Protocol specification
const ( // TargetTypeTool represents a tool target TargetTypeTool = "tool" // TargetTypeResource represents a resource target TargetTypeResource = "resource" // TargetTypePrompt represents a prompt target TargetTypePrompt = "prompt" // TargetTypeServer represents a server target TargetTypeServer = "server" // TargetTypeWorkflow represents a workflow target TargetTypeWorkflow = "workflow" // TargetTypeWorkflowStep represents a workflow step target TargetTypeWorkflowStep = "workflow_step" )
MCP target types for audit events
const ( // TargetKeyType is the key for the target type in the target map TargetKeyType = "type" // TargetKeyName is the key for the target name in the target map TargetKeyName = "name" // TargetKeyURI is the key for the target URI in the target map TargetKeyURI = "uri" // TargetKeyMethod is the key for the MCP method in the target map TargetKeyMethod = "method" // TargetKeyEndpoint is the key for the endpoint in the target map TargetKeyEndpoint = "endpoint" // TargetKeyWorkflowID is the key for the unique workflow execution ID TargetKeyWorkflowID = "workflow_id" // TargetKeyWorkflowName is the key for the workflow definition name TargetKeyWorkflowName = "workflow_name" // TargetKeyStepID is the key for the step identifier TargetKeyStepID = "step_id" // TargetKeyStepType is the key for the step type (tool, elicitation) TargetKeyStepType = "step_type" // TargetKeyToolName is the key for the tool being called (for tool steps) TargetKeyToolName = "tool_name" )
MCP-specific target field keys
const ( // SubjectKeyUser is the key for the user in the subjects map SubjectKeyUser = "user" // SubjectKeyUserID is the key for the user ID in the subjects map SubjectKeyUserID = "user_id" // SubjectKeyClientName is the key for the client name in the subjects map SubjectKeyClientName = "client_name" // SubjectKeyClientVersion is the key for the client version in the subjects map SubjectKeyClientVersion = "client_version" )
MCP-specific subject field keys
const ( // SourceExtraKeyUserAgent is the key for the user agent in the source extra map SourceExtraKeyUserAgent = "user_agent" // SourceExtraKeyRequestID is the key for the request ID in the source extra map SourceExtraKeyRequestID = "request_id" // SourceExtraKeySessionID is the key for the session ID in the source extra map SourceExtraKeySessionID = "session_id" )
MCP-specific source field keys for EventSource.Extra
const ( // MetadataExtraKeyMCPVersion is the key for the MCP version in the metadata extra map MetadataExtraKeyMCPVersion = "mcp_version" // MetadataExtraKeyTransport is the key for the transport type in the metadata extra map MetadataExtraKeyTransport = "transport" // MetadataExtraKeyDuration is the key for the request duration in the metadata extra map MetadataExtraKeyDuration = "duration_ms" // MetadataExtraKeyResponseSize is the key for the response size in the metadata extra map MetadataExtraKeyResponseSize = "response_size_bytes" // MetadataExtraKeyRetryCount is the key for the number of retries performed MetadataExtraKeyRetryCount = "retry_count" // MetadataExtraKeyStepCount is the key for the total number of steps in a workflow MetadataExtraKeyStepCount = "step_count" // MetadataExtraKeyTimeout is the key for the workflow timeout in milliseconds MetadataExtraKeyTimeout = "timeout_ms" )
MCP-specific metadata field keys for EventMetadata.Extra
const ( // ComponentToolHive is the component name for ToolHive API audit events. // Note that events directed for an MCP server will have the name of the // MCP server as the component instead. ComponentToolHive = "toolhive-api" )
Component name for ToolHive
const LevelAudit = slog.Level(2)
LevelAudit is a custom audit log level - between Info and Warn
const (
MiddlewareType = "audit"
)
Middleware type constant
Variables ¶
This section is empty.
Functions ¶
func CreateMiddleware ¶ added in v0.2.8
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
CreateMiddleware factory function for audit middleware
func GetMiddlewareFromFile ¶
func GetMiddlewareFromFile(path string, transportType string) (func(http.Handler) http.Handler, error)
GetMiddlewareFromFile loads the audit configuration from a file and creates an HTTP middleware. Note: This function requires a transport type to be provided separately.
func NewAuditLogger ¶ added in v0.0.46
NewAuditLogger creates a new structured audit logger that writes to the specified writer.
func WithBackendInfo ¶ added in v0.6.12
func WithBackendInfo(ctx context.Context, info *BackendInfo) context.Context
WithBackendInfo returns a new context with BackendInfo attached.
Types ¶
type AuditEvent ¶
type AuditEvent struct {
Metadata EventMetadata `json:"metadata"`
// Type: Defines the type of event that occurred
// This is a small identifier to quickly determine what happened.
// e.g. UserLogin, UserLogout, UserCreate, UserDelete, etc.
Type string `json:"type"`
// LoggedAt: determines when the event occurred.
// Note that this should have sufficient information to authoritatively
// determine the exact time the event was logged at. The output must be in
// Coordinated Universal Time (UTC) format, a modern continuation of
// Greenwich Mean Time (GMT), or local time with an offset from UTC to satisfy
// NIST SP 800-53 requirement AU-8.
LoggedAt time.Time `json:"loggedAt"`
// Source: determines the source of the event.
// Normally, using the IP address of the client, or pod name is sufficient.
// One must be careful of the data that's added here as we don't want to
// leak Personally Identifiable Information.
Source EventSource `json:"source"`
// Outcome: determines whether the event was successful or not, e.g. successful login
// It may also determine if the event was approved or denied.
Outcome string `json:"outcome"`
// Subject: is the identity of the subject of the event.
// e.g. who triggered the event? Additional information
// may be added, such as group membership and/or role
Subjects map[string]string `json:"subjects"`
// Component: allows to determine in which component the event occurred
// (Answering the "Where" question of section c in the NIST SP 800-53
// Revision 5.1 Control AU-3).
Component string `json:"component"`
// Target: Defines where the target of the operation. e.g. the path of
// the REST resource
// (Answering the "Where" question of section c in the NIST SP 800-53
// Revision 5.1 Control AU-3 as well as indicating an entity
// associated for section f).
Target map[string]string `json:"target,omitempty"`
// Data: enhances the audit event with extra information that may be
// useful for forensic analysis.
Data *json.RawMessage `json:"data,omitempty"`
}
AuditEvent represents an audit event. It provides the minimal information needed to audit an event, as well as a uniform format to persist the events in audit logs.
It is highly recommended to use the NewAuditEvent function to create audit events and set the required fields.
func NewAuditEvent ¶
func NewAuditEvent( eventType string, source EventSource, outcome string, subjects map[string]string, component string, ) *AuditEvent
NewAuditEvent returns a new AuditEvent with an appropriately set AuditID and logging time.
func NewAuditEventWithID ¶
func NewAuditEventWithID( auditID string, eventType string, source EventSource, outcome string, subjects map[string]string, component string, ) *AuditEvent
NewAuditEventWithID returns a new AuditEvent with the passed AuditID.
func (*AuditEvent) LogTo ¶ added in v0.0.46
LogTo logs the audit event to the provided slog.Logger using the custom audit level.
func (*AuditEvent) WithData ¶
func (e *AuditEvent) WithData(data *json.RawMessage) *AuditEvent
WithData sets the data of the event.
func (*AuditEvent) WithDataFromString ¶
func (e *AuditEvent) WithDataFromString(data string) *AuditEvent
WithDataFromString sets the data of the event from a string. Note that validating that this is properly JSON-formatted is the responsibility of the caller.
func (*AuditEvent) WithTarget ¶
func (e *AuditEvent) WithTarget(target map[string]string) *AuditEvent
WithTarget sets the target of the event.
type Auditor ¶
type Auditor struct {
// contains filtered or unexported fields
}
Auditor handles audit logging for HTTP requests.
func NewAuditorWithTransport ¶ added in v0.3.7
NewAuditorWithTransport creates a new Auditor with the given configuration and transport information.
type BackendInfo ¶ added in v0.6.12
type BackendInfo struct {
BackendName string
}
BackendInfo stores backend routing information that can be mutated by handlers. This allows handlers deep in the call stack to provide backend info to the audit middleware.
func BackendInfoFromContext ¶ added in v0.6.12
func BackendInfoFromContext(ctx context.Context) (*BackendInfo, bool)
BackendInfoFromContext retrieves BackendInfo from the context. Returns (nil, false) if BackendInfo is not found in the context.
type Config ¶
type Config struct {
// Enabled controls whether audit logging is enabled.
// When true, enables audit logging with the configured options.
// +kubebuilder:default=false
// +optional
Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`
// Component is the component name to use in audit events.
// +optional
Component string `json:"component,omitempty" yaml:"component,omitempty"`
// EventTypes specifies which event types to audit. If empty, all events are audited.
// +optional
EventTypes []string `json:"eventTypes,omitempty" yaml:"eventTypes,omitempty"`
// ExcludeEventTypes specifies which event types to exclude from auditing.
// This takes precedence over EventTypes.
// +optional
ExcludeEventTypes []string `json:"excludeEventTypes,omitempty" yaml:"excludeEventTypes,omitempty"`
// IncludeRequestData determines whether to include request data in audit logs.
// +kubebuilder:default=false
// +optional
IncludeRequestData bool `json:"includeRequestData,omitempty" yaml:"includeRequestData,omitempty"`
// IncludeResponseData determines whether to include response data in audit logs.
// +kubebuilder:default=false
// +optional
IncludeResponseData bool `json:"includeResponseData,omitempty" yaml:"includeResponseData,omitempty"`
// MaxDataSize limits the size of request/response data included in audit logs (in bytes).
// +kubebuilder:default=1024
// +optional
MaxDataSize int `json:"maxDataSize,omitempty" yaml:"maxDataSize,omitempty"`
// LogFile specifies the file path for audit logs. If empty, logs to stdout.
// +optional
LogFile string `json:"logFile,omitempty" yaml:"logFile,omitempty"`
}
Config represents the audit logging configuration. +kubebuilder:object:generate=true +gendoc
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a default audit configuration.
func LoadFromFile ¶
LoadFromFile loads audit configuration from a file.
func LoadFromReader ¶
LoadFromReader loads audit configuration from an io.Reader.
func (*Config) CreateMiddlewareWithTransport ¶ added in v0.3.7
func (c *Config) CreateMiddlewareWithTransport(transportType string) (types.MiddlewareFunction, error)
CreateMiddlewareWithTransport creates an HTTP middleware from the audit configuration with transport information.
func (*Config) DeepCopy ¶ added in v0.6.17
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config.
func (*Config) DeepCopyInto ¶ added in v0.6.17
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (*Config) GetLogWriter ¶ added in v0.0.46
GetLogWriter creates and returns the appropriate io.Writer based on the configuration.
func (*Config) ShouldAuditEvent ¶
ShouldAuditEvent determines whether an event should be audited based on the configuration.
type EventMetadata ¶
type EventMetadata struct {
// AuditID: is a unique identifier for the audit event.
AuditID string `json:"auditId"`
// Extra allows for including additional information about the event
// that aids in tracking, parsing or auditing
Extra map[string]any `json:"extra,omitempty"`
}
EventMetadata contains metadata about the audit event.
type EventSource ¶
type EventSource struct {
// Type indicates the source type. e.g. Network, File, local, etc.
// The intent is to determine where a request came from.
Type string `json:"type"`
// Value aims to indicate the source of the event. e.g. IP address,
// hostname, etc.
Value string `json:"value"`
// Extra allows for including additional information about the event
// source that aids in tracking, parsing or auditing
Extra map[string]any `json:"extra,omitempty"`
}
EventSource represents the source of an audit event.
type Middleware ¶ added in v0.2.8
type Middleware struct {
// contains filtered or unexported fields
}
Middleware wraps audit middleware functionality
func (*Middleware) Close ¶ added in v0.2.8
func (*Middleware) Close() error
Close cleans up any resources used by the middleware.
func (*Middleware) Handler ¶ added in v0.2.8
func (m *Middleware) Handler() types.MiddlewareFunction
Handler returns the middleware function used by the proxy.
type MiddlewareParams ¶ added in v0.2.8
type MiddlewareParams struct {
ConfigPath string `json:"config_path,omitempty"` // Kept for backwards compatibility
ConfigData *Config `json:"config_data,omitempty"` // New field for config contents
Component string `json:"component,omitempty"`
// Transport information for dynamic transport detection
TransportType string `json:"transport_type,omitempty"` // e.g., "sse", "streamable-http"
}
MiddlewareParams represents the parameters for audit middleware
type WorkflowAuditor ¶ added in v0.6.14
type WorkflowAuditor struct {
// contains filtered or unexported fields
}
WorkflowAuditor provides audit logging for workflow execution. This struct abstracts workflow-specific audit operations from the HTTP middleware-based Auditor.
func NewWorkflowAuditor ¶ added in v0.6.14
func NewWorkflowAuditor(config *Config) (*WorkflowAuditor, error)
NewWorkflowAuditor creates a new workflow auditor. If config is nil, creates a default configuration with stdout logging.
func (*WorkflowAuditor) LogStepCompleted ¶ added in v0.6.14
func (w *WorkflowAuditor) LogStepCompleted( ctx context.Context, workflowID string, stepID string, duration time.Duration, retryCount int, )
LogStepCompleted logs successful step completion.
func (*WorkflowAuditor) LogStepFailed ¶ added in v0.6.14
func (w *WorkflowAuditor) LogStepFailed( ctx context.Context, workflowID string, stepID string, duration time.Duration, retryCount int, _ error, )
LogStepFailed logs step failure.
func (*WorkflowAuditor) LogStepSkipped ¶ added in v0.6.14
func (w *WorkflowAuditor) LogStepSkipped( ctx context.Context, workflowID string, stepID string, condition string, )
LogStepSkipped logs conditional step skip.
func (*WorkflowAuditor) LogStepStarted ¶ added in v0.6.14
func (w *WorkflowAuditor) LogStepStarted( ctx context.Context, workflowID string, stepID string, stepType string, toolName string, )
LogStepStarted logs the start of step execution.
func (*WorkflowAuditor) LogWorkflowCompleted ¶ added in v0.6.14
func (w *WorkflowAuditor) LogWorkflowCompleted( ctx context.Context, workflowID string, workflowName string, duration time.Duration, stepCount int, output map[string]any, )
LogWorkflowCompleted logs successful workflow completion.
func (*WorkflowAuditor) LogWorkflowFailed ¶ added in v0.6.14
func (w *WorkflowAuditor) LogWorkflowFailed( ctx context.Context, workflowID string, workflowName string, duration time.Duration, stepCount int, _ error, )
LogWorkflowFailed logs workflow failure.
func (*WorkflowAuditor) LogWorkflowStarted ¶ added in v0.6.14
func (w *WorkflowAuditor) LogWorkflowStarted( ctx context.Context, workflowID string, workflowName string, parameters map[string]any, timeout time.Duration, )
LogWorkflowStarted logs the start of workflow execution.
func (*WorkflowAuditor) LogWorkflowTimedOut ¶ added in v0.6.14
func (w *WorkflowAuditor) LogWorkflowTimedOut( ctx context.Context, workflowID string, workflowName string, duration time.Duration, stepCount int, )
LogWorkflowTimedOut logs workflow timeout.