Documentation
¶
Overview ¶
Package audit contains domain types for audit logging.
Index ¶
- Constants
- Variables
- func RedactSensitiveArgs(args map[string]interface{}) map[string]interface{}
- type AuditFilter
- type AuditQueryStore
- type AuditRecord
- type AuditStats
- type AuditStore
- type ComplianceAuditFilter
- type ComplianceAuditRecord
- type ComplianceAuditStore
- type ComplianceStats
- type DetectionStats
- type ScanResultHolder
- type ToolCallStats
Constants ¶
const ( // DecisionAllow indicates the tool call was permitted. DecisionAllow = "allow" // DecisionDeny indicates the tool call was blocked. DecisionDeny = "deny" )
Decision constants for audit records.
const ( // EventTypeToolCall is the default event type for tool invocations. EventTypeToolCall = "tool_call" // SOC2-01: Access control events (CC6) EventTypeLogin = "access.login" EventTypeLogout = "access.logout" EventTypeLoginFailed = "access.login_failed" EventTypePermissionGrant = "access.permission_grant" EventTypePermissionRevoke = "access.permission_revoke" EventTypeAPIKeyCreate = "access.api_key_create" EventTypeAPIKeyRevoke = "access.api_key_revoke" // SOC2-02: Configuration changes (CC7, CC8) EventTypePolicyCreate = "config.policy_create" EventTypePolicyUpdate = "config.policy_update" EventTypePolicyDelete = "config.policy_delete" EventTypeScanConfigUpdate = "config.scan_update" EventTypeSSOConfigUpdate = "config.sso_update" EventTypeTenantUpdate = "config.tenant_update" // SOC2-03: User lifecycle events (CC6) EventTypeUserCreate = "user.create" EventTypeUserModify = "user.modify" EventTypeUserDisable = "user.disable" EventTypeUserDelete = "user.delete" EventTypeUserEnable = "user.enable" )
EventType constants for compliance audit records. Categorized by SOC 2 Trust Services Criteria requirements.
const ( ActorTypeAdmin = "admin" ActorTypeUser = "user" ActorTypeSystem = "system" ActorTypeAPIKey = "api_key" )
ActorType constants identify who performed an action.
Variables ¶
var ( // ErrDateRangeExceeded is returned when the query date range exceeds the maximum allowed. ErrDateRangeExceeded = errors.New("date range exceeds maximum of 7 days") )
Sentinel errors for audit store operations.
Functions ¶
func RedactSensitiveArgs ¶
RedactSensitiveArgs returns a copy of args with sensitive values masked. A key is considered sensitive if it contains any of the sensitiveKeywords (case-insensitive). Values are replaced with "***REDACTED***".
Types ¶
type AuditFilter ¶
type AuditFilter struct {
// StartTime is the beginning of the time range (required).
StartTime time.Time
// EndTime is the end of the time range (required).
EndTime time.Time
// UserID filters by identity ID (optional).
UserID string
// SessionID filters by session ID (optional).
SessionID string
// ToolName filters by tool name (optional).
ToolName string
// Decision filters by decision (optional: "allow" or "deny").
Decision string
// Protocol filters by originating protocol (optional: "mcp", "http", "websocket", "runtime").
Protocol string
// Limit is the maximum number of records to return (default 100, max 100).
Limit int
// Cursor is the pagination cursor for fetching next page (optional).
Cursor string
}
AuditFilter specifies query parameters for audit log queries.
type AuditQueryStore ¶
type AuditQueryStore interface {
// Query retrieves audit records matching the filter.
// Returns records, next cursor (empty if no more pages), and error.
// Returns ErrDateRangeExceeded if EndTime - StartTime > 7 days.
Query(ctx context.Context, filter AuditFilter) ([]AuditRecord, string, error)
// QueryStats returns aggregated statistics for the given time range.
// This supports EU AI Act transparency reporting requirements.
QueryStats(ctx context.Context, start, end time.Time) (*AuditStats, error)
}
AuditQueryStore provides read access to audit logs for admin queries. This interface is separate from AuditStore which handles writes.
type AuditRecord ¶
type AuditRecord struct {
// Timestamp is when the tool call was received.
Timestamp time.Time
// SessionID from the authenticated session.
SessionID string
// IdentityID of the user making the call.
IdentityID string
// IdentityName is the human-readable name (resolved from IdentityID).
IdentityName string
// ToolName is the name of the tool being invoked.
ToolName string
// ToolArguments are the arguments passed to the tool (may be redacted).
ToolArguments map[string]interface{}
// Decision is "allow" or "deny".
Decision string
// Reason explains why the decision was made.
Reason string
// RuleID is the ID of the rule that matched (if any).
RuleID string
// RequestID is for correlation across systems.
RequestID string
// LatencyMicros is the policy evaluation latency in microseconds.
LatencyMicros int64
// Scan detection info (added for Phase 14)
// ScanDetections is the number of sensitive content detections found.
ScanDetections int
// ScanAction is the action taken: "blocked", "redacted", "flagged", or empty (none).
ScanAction string
// ScanTypes is a comma-separated list of detection types (e.g., "secret,pii").
ScanTypes string
// Protocol is the originating protocol (mcp, http, websocket, runtime).
Protocol string
// Framework is the detected framework (langchain, crewai, autogen, openai-agents-sdk, or empty).
Framework string
}
AuditRecord represents a single auditable event from a tool call.
type AuditStats ¶
type AuditStats struct {
// TotalCalls is the total number of tool call audit records.
TotalCalls int64
// UniqueIdentities is the count of distinct identity IDs.
UniqueIdentities int64
// UniqueSessions is the count of distinct session IDs.
UniqueSessions int64
// ByTool maps tool names to per-tool statistics.
ByTool map[string]ToolCallStats
// ByDecision maps decision values to counts.
ByDecision map[string]int64
// Detections contains content scanning detection counts.
Detections DetectionStats
}
AuditStats contains aggregated audit statistics for a time period. Used for transparency reporting per EU AI Act requirements.
type AuditStore ¶
type AuditStore interface {
// Append stores audit records. Must be non-blocking from caller perspective.
Append(ctx context.Context, records ...AuditRecord) error
// Flush forces pending records to storage. Called during shutdown.
Flush(ctx context.Context) error
// Close releases resources.
Close() error
}
AuditStore persists audit records. Interface owned by domain per hexagonal architecture. Implementation handles batching and async writes.
type ComplianceAuditFilter ¶
type ComplianceAuditFilter struct {
// StartTime is the beginning of the time range (required).
StartTime time.Time
// EndTime is the end of the time range (required).
EndTime time.Time
// EventTypes filters by specific event types (optional).
EventTypes []string
// ActorID filters by the actor who performed the action (optional).
ActorID string
// TargetID filters by the target of the action (optional).
TargetID string
// Limit is the maximum number of records to return (default 100, max 1000).
Limit int
// Cursor is the pagination cursor for fetching next page (optional).
Cursor string
}
ComplianceAuditFilter specifies query parameters for compliance audit queries.
type ComplianceAuditRecord ¶
type ComplianceAuditRecord struct {
// Timestamp when the event occurred.
Timestamp time.Time `json:"timestamp"`
// TenantID for multi-tenant isolation.
TenantID string `json:"tenant_id"`
// EventType categorizes the event (access.*, config.*, user.*).
EventType string `json:"event_type"`
// RequestID for correlation across systems.
RequestID string `json:"request_id"`
// Actor information (who performed the action)
ActorID string `json:"actor_id"`
ActorType string `json:"actor_type"` // admin, user, system, api_key
ActorUsername string `json:"actor_username,omitempty"`
// Target information (what was affected)
TargetID string `json:"target_id,omitempty"`
TargetType string `json:"target_type,omitempty"` // user, policy, config, etc.
TargetName string `json:"target_name,omitempty"`
// Change details
OldValue string `json:"old_value,omitempty"` // JSON-encoded previous state
NewValue string `json:"new_value,omitempty"` // JSON-encoded new state
// Additional context
SourceIP string `json:"source_ip,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Reason string `json:"reason,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
ComplianceAuditRecord extends AuditRecord for SOC 2 compliance events. Used for access control, configuration changes, and user lifecycle events.
type ComplianceAuditStore ¶
type ComplianceAuditStore interface {
// Append stores compliance audit records.
Append(ctx context.Context, records ...ComplianceAuditRecord) error
// Query retrieves compliance audit records matching the filter.
// Returns records, next cursor for pagination, and error.
Query(ctx context.Context, filter ComplianceAuditFilter) ([]ComplianceAuditRecord, string, error)
// QueryStats returns aggregated compliance statistics for the given time range.
QueryStats(ctx context.Context, start, end time.Time) (*ComplianceStats, error)
// PurgeOlderThan deletes compliance audit records older than the specified date.
// This is used for retention management and should only be called after
// verifying no active legal holds cover the affected time range.
// Returns the number of records deleted.
PurgeOlderThan(ctx context.Context, before time.Time) (int64, error)
}
ComplianceAuditStore handles SOC 2 compliance audit records. These are separate from tool call audit records as they track access control, configuration changes, and user lifecycle events.
type ComplianceStats ¶
type ComplianceStats struct {
// TotalEvents is the total count of compliance events.
TotalEvents int64
// AccessEvents is the count of access.* events.
AccessEvents int64
// ConfigChanges is the count of config.* events.
ConfigChanges int64
// UserLifecycleEvents is the count of user.* events.
UserLifecycleEvents int64
// FailedLogins is the count of access.login_failed events.
FailedLogins int64
// PolicyDenials is the count of tool_call events with denial reason.
PolicyDenials int64
// EventsByType maps event types to counts.
EventsByType map[string]int64
}
ComplianceStats contains aggregated compliance statistics.
type DetectionStats ¶
type DetectionStats struct {
// SecretsFound is the count of secret detections.
SecretsFound int64
// PIIFound is the count of PII detections.
PIIFound int64
// InjectionsFound is the count of injection attempt detections.
InjectionsFound int64
}
DetectionStats contains content scanning detection counts.
type ScanResultHolder ¶
type ScanResultHolder struct {
// Detections is the number of scan findings.
Detections int
// Action is the action taken: "blocked" (enforce) or "monitored" (monitor).
Action string
// Types is a comma-separated list of unique finding categories (e.g., "prompt_injection").
Types string
}
ScanResultHolder is a mutable container placed in context by the AuditInterceptor. Downstream interceptors (e.g., ResponseScanInterceptor) populate it with scan findings. The AuditInterceptor reads it after the chain completes to populate audit record scan fields.
func NewScanResultContext ¶
func NewScanResultContext(ctx context.Context) (context.Context, *ScanResultHolder)
NewScanResultContext returns a new context with an empty ScanResultHolder. The AuditInterceptor calls this before invoking the chain.
func ScanResultFromContext ¶
func ScanResultFromContext(ctx context.Context) *ScanResultHolder
ScanResultFromContext retrieves the ScanResultHolder from context. Returns nil if not present.
type ToolCallStats ¶
type ToolCallStats struct {
// Calls is the total number of calls to this tool.
Calls int64
// Allowed is the number of calls that were allowed.
Allowed int64
// Denied is the number of calls that were denied.
Denied int64
}
ToolCallStats contains per-tool audit statistics.