safety

package
v0.0.0-...-f2e6f42 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 19, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package safety provides security filters and risk classification for administrative operations.

Package safety provides security filters and risk management for GitHub administrative operations.

The safety system implements a 4-tier risk classification (LOW/MEDIUM/HIGH/CRITICAL) with configurable safeguards including dry-run previews, confirmation tokens, automatic backups, and comprehensive audit logging.

Index

Constants

View Source
const (
	// DefaultAuditLogPath is the default location for audit logs
	DefaultAuditLogPath = "./mcp-admin-audit.log"

	// DefaultMaxLogSize is the default maximum log file size (10MB)
	DefaultMaxLogSize = 10 * 1024 * 1024

	// DefaultMaxBackups is the default number of backup files to keep
	DefaultMaxBackups = 5
)
View Source
const (
	// TokenExpiration is the duration before a token expires
	TokenExpiration = 5 * time.Minute

	// TokenPrefix is prepended to all tokens for identification
	TokenPrefix = "CONF:"
)

Variables

This section is empty.

Functions

func CleanupAllExpiredTokens

func CleanupAllExpiredTokens() int

CleanupAllExpiredTokens removes all expired tokens (for maintenance)

func CleanupOldLogs

func CleanupOldLogs(logDir string, daysToKeep int) error

CleanupOldLogs removes audit log files older than specified days

func ClearAllTokens

func ClearAllTokens()

ClearAllTokens removes all tokens (for testing)

func FormatRollbackCommand

func FormatRollbackCommand(operation string, originalParams map[string]interface{}) string

FormatRollbackCommand generates a rollback command for an operation

func GetActiveTokens

func GetActiveTokens() int

GetActiveTokens returns the count of active tokens

func GetConfirmationMessage

func GetConfirmationMessage(token *ConfirmationToken, additionalInfo string) string

GetConfirmationMessage returns a formatted message for requesting confirmation

func GetOperationsByCategory

func GetOperationsByCategory(category string) []string

GetOperationsByCategory returns all operations in a specific category

func GetOperationsByRiskLevel

func GetOperationsByRiskLevel(level RiskLevel) []string

GetOperationsByRiskLevel returns all operations at a specific risk level

func GetStatistics

func GetStatistics(logPath string) (map[string]interface{}, error)

GetStatistics returns statistics from audit log

func IsAdminOperation

func IsAdminOperation(operation string) bool

IsAdminOperation checks if an operation is administrative. Accepts both consolidated tool names ("github_admin_repo") and composite keys ("github_admin_repo:get_settings").

func LogOperation

func LogOperation(entry *AuditEntry) error

LogOperation logs an administrative operation

func SetDefaultLogger

func SetDefaultLogger(logger *AuditLogger)

SetDefaultLogger sets the global default audit logger

func ValidateConfirmationToken

func ValidateConfirmationToken(tokenStr string, operation string, parameters map[string]interface{}) error

ValidateConfirmationToken verifies a confirmation token and marks it as used

func ValidateParameters

func ValidateParameters(operation string, parameters map[string]interface{}) error

ValidateParameters validates all parameters for an operation

func ValidateSafeInput

func ValidateSafeInput(input string) error

ValidateSafeInput validates general input for command injection

func ValidateSafePath

func ValidateSafePath(path string) error

ValidateSafePath validates file path for security (prevents path traversal)

Types

type AuditEntry

type AuditEntry struct {
	Timestamp         time.Time              `json:"timestamp"`
	Operation         string                 `json:"operation"`
	RiskLevel         string                 `json:"risk_level"`
	Arguments         map[string]interface{} `json:"arguments"`
	Result            string                 `json:"result"` // success, failed, partial
	Changes           []string               `json:"changes,omitempty"`
	RollbackCommand   string                 `json:"rollback_cmd,omitempty"`
	ConfirmationToken string                 `json:"confirmation_token,omitempty"`
	ExecutionTimeMs   int64                  `json:"execution_time_ms"`
	ErrorMessage      string                 `json:"error_message,omitempty"`
}

AuditEntry represents a single audit log entry

func FilterEntriesByOperation

func FilterEntriesByOperation(entries []*AuditEntry, operation string) []*AuditEntry

FilterEntriesByOperation filters audit entries by operation name

func FilterEntriesByResult

func FilterEntriesByResult(entries []*AuditEntry, result string) []*AuditEntry

FilterEntriesByResult filters audit entries by result status

func FilterEntriesByRiskLevel

func FilterEntriesByRiskLevel(entries []*AuditEntry, riskLevel string) []*AuditEntry

FilterEntriesByRiskLevel filters audit entries by risk level

func GetRecentEntries

func GetRecentEntries(logPath string, count int) ([]*AuditEntry, error)

GetRecentEntries returns the N most recent audit entries

func ReadAuditLog

func ReadAuditLog(logPath string) ([]*AuditEntry, error)

ReadAuditLog reads and parses audit log entries

type AuditLogger

type AuditLogger struct {
	// contains filtered or unexported fields
}

AuditLogger manages audit trail logging

func NewAuditLogger

func NewAuditLogger(logPath string, enabled bool) *AuditLogger

NewAuditLogger creates a new audit logger

func (*AuditLogger) GetLogPath

func (l *AuditLogger) GetLogPath() string

GetLogPath returns the current log file path

func (*AuditLogger) IsEnabled

func (l *AuditLogger) IsEnabled() bool

IsEnabled returns whether audit logging is enabled

func (*AuditLogger) LogOperation

func (l *AuditLogger) LogOperation(entry *AuditEntry) error

LogOperation logs an administrative operation using this logger

func (*AuditLogger) SetEnabled

func (l *AuditLogger) SetEnabled(enabled bool)

SetEnabled enables or disables audit logging

type ConfirmationToken

type ConfirmationToken struct {
	Token      string                 // Hex-encoded token (CONF:abc123...)
	Operation  string                 // Tool name
	Parameters map[string]interface{} // Sanitized parameters
	ExpiresAt  time.Time              // Token expiration (5 minutes)
	RiskLevel  RiskLevel              // Risk level of operation
	Used       bool                   // Whether token has been used
	CreatedAt  time.Time              // Creation timestamp
}

ConfirmationToken represents a single-use token for confirming high-risk operations

func GenerateConfirmationToken

func GenerateConfirmationToken(operation string, parameters map[string]interface{}, riskLevel RiskLevel) (*ConfirmationToken, error)

GenerateConfirmationToken creates a new confirmation token for a high-risk operation

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is the main safety engine that orchestrates all safety checks

func NewEngine

func NewEngine(config *SafetyConfig) *Engine

NewEngine creates a new safety engine with the given configuration

func (*Engine) CheckOperation

func (e *Engine) CheckOperation(ctx context.Context, operation string, parameters map[string]interface{}) (*SafetyCheck, error)

CheckOperation performs a comprehensive safety check for an operation

func (*Engine) CreateBackup

func (e *Engine) CreateBackup(operation string, data interface{}) (string, error)

CreateBackup creates a backup of operation parameters before a destructive operation

func (*Engine) GetConfig

func (e *Engine) GetConfig() *SafetyConfig

GetConfig returns the current safety configuration

func (*Engine) GetLogger

func (e *Engine) GetLogger() *AuditLogger

GetLogger returns the audit logger

func (*Engine) GetStatistics

func (e *Engine) GetStatistics() (map[string]interface{}, error)

GetStatistics returns audit log statistics

func (*Engine) LogOperationResult

func (e *Engine) LogOperationResult(operation string, risk OperationRisk, parameters map[string]interface{}, result string, changes []string, rollbackCmd string, executionTime time.Duration, err error) error

LogOperationResult logs the result of an operation to the audit trail

func (*Engine) PreviewOperation

func (e *Engine) PreviewOperation(ctx context.Context, operation string, parameters map[string]interface{}) (string, error)

PreviewOperation returns what will happen without executing

func (*Engine) UpdateConfig

func (e *Engine) UpdateConfig(config *SafetyConfig)

UpdateConfig updates the safety configuration

type OperationRisk

type OperationRisk struct {
	Level                RiskLevel
	RequiresDryRun       bool
	RequiresConfirmation bool
	RequiresBackup       bool
	RequiresAudit        bool
	Category             string
	Description          string
}

OperationRisk defines the risk profile and required safeguards for an operation

func ClassifyOperation

func ClassifyOperation(operation string) (OperationRisk, bool)

ClassifyOperation returns the risk profile for a given operation. Accepts both composite keys "tool:operation" and legacy tool names.

type RiskLevel

type RiskLevel int

RiskLevel represents the danger level of an operation

const (
	// RiskLow - Read-only, informational operations with no side effects
	RiskLow RiskLevel = 1

	// RiskMedium - Modifications that are easily reversible
	RiskMedium RiskLevel = 2

	// RiskHigh - Destructive operations that impact team collaboration
	RiskHigh RiskLevel = 3

	// RiskCritical - Irreversible or high security impact operations
	RiskCritical RiskLevel = 4
)

func (RiskLevel) String

func (r RiskLevel) String() string

String returns the string representation of the risk level

type SafetyCheck

type SafetyCheck struct {
	Operation            string
	Risk                 OperationRisk
	RequiresDryRun       bool
	RequiresConfirmation bool
	RequiresBackup       bool
	ValidationErrors     []error
	CanProceed           bool
	Message              string
}

SafetyCheck holds the result of a safety check

type SafetyConfig

type SafetyConfig struct {
	Mode                     SafetyMode
	EnableAuditLog           bool
	AuditLogPath             string
	RequireConfirmationAbove RiskLevel
	RequireDryRunAbove       RiskLevel
	EnableAutoBackup         bool
	BackupPath               string
}

SafetyConfig holds the safety system configuration

func DefaultConfig

func DefaultConfig() *SafetyConfig

DefaultConfig returns the default safety configuration (moderate mode)

type SafetyMode

type SafetyMode string

SafetyMode represents the safety configuration mode

const (
	// SafetyModeStrict enforces maximum safety (dry-run forced, confirmations for MEDIUM+)
	SafetyModeStrict SafetyMode = "strict"

	// SafetyModeModerate balanced safety (confirmations for HIGH+, optional dry-run)
	SafetyModeModerate SafetyMode = "moderate"

	// SafetyModePermissive minimal restrictions (confirmations for CRITICAL only)
	SafetyModePermissive SafetyMode = "permissive"

	// SafetyModeDisabled bypasses all safety checks (use with caution!)
	SafetyModeDisabled SafetyMode = "disabled"
)

type ValidationError

type ValidationError struct {
	Parameter string
	Value     interface{}
	Reason    string
}

ValidationError represents a validation failure

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Validator

type Validator func(param string, value interface{}) error

Validator is a function that validates a parameter value

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL