approval

package
v0.4.21 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package approval provides intelligent command approval system inspired by Cortex Agent's Smart Approvals. It features command normalization, risk assessment, session learning, approval history, statistics, and web-based approval callbacks.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ApprovalCallback

type ApprovalCallback interface {
	OnApproval(result *ApprovalResult, req *ApprovalRequest)
	OnApprovalTimeout(req *ApprovalRequest)
}

ApprovalCallback is called on approval decisions.

type ApprovalConfig

type ApprovalConfig struct {
	Strategy          Strategy `mapstructure:"strategy"`
	TrustThreshold    int      `mapstructure:"trust_threshold"`
	DenylistThreshold int      `mapstructure:"denylist_threshold"`
	EnableLearning    bool     `mapstructure:"enable_learning"`
	EnableWhitelist   bool     `mapstructure:"enable_whitelist"`
	EnableCLIConfirm  bool     `mapstructure:"enable_cli_confirm"`
	GatewayEnabled    bool     `mapstructure:"gateway_enabled"`
	GatewayURL        string   `mapstructure:"gateway_url"`
	DangerousPatterns []string `mapstructure:"dangerous_patterns"`
	AllowedPatterns   []string `mapstructure:"allowed_patterns"`
	ApprovalTimeout   int      `mapstructure:"approval_timeout"`
	LearnFromSameUser bool     `mapstructure:"learn_from_same_user"`
}

ApprovalConfig holds approval system configuration.

func DefaultConfig

func DefaultConfig() *ApprovalConfig

DefaultConfig returns the default approval configuration.

type ApprovalRecord added in v0.4.10

type ApprovalRecord struct {
	ID         string    `json:"id"`
	Command    string    `json:"command"`
	Normalized string    `json:"normalized"`
	RiskLevel  RiskLevel `json:"risk_level"`
	RiskScore  float64   `json:"risk_score"`
	Category   string    `json:"category"` // risk category
	Decision   string    `json:"decision"` // approved, denied, auto_approved, timeout
	Strategy   Strategy  `json:"strategy"`
	Reason     string    `json:"reason"`
	SessionID  string    `json:"session_id"`
	WorkingDir string    `json:"working_dir"`
	Duration   int64     `json:"duration_ms"` // 审批耗时
	Timestamp  time.Time `json:"timestamp"`
}

ApprovalRecord 审批历史记录.

type ApprovalRequest

type ApprovalRequest struct {
	Command    string
	Args       []string
	WorkingDir string
	Env        map[string]string
	SessionID  string
	UserID     string
	RiskLevel  RiskLevel
	Category   string // risk category from assessment
	Reason     string
	Timestamp  time.Time
}

ApprovalRequest represents a command approval request.

type ApprovalResult

type ApprovalResult struct {
	Approved  bool
	Strategy  Strategy
	Reason    string
	Trusted   bool
	AskUser   bool
	RiskLevel RiskLevel
	Pattern   *CommandPattern
}

ApprovalResult is the result of an approval decision.

type ApprovalStats added in v0.4.10

type ApprovalStats struct {
	TotalRequests   int               `json:"total_requests"`
	AutoApproved    int               `json:"auto_approved"`
	UserApproved    int               `json:"user_approved"`
	UserDenied      int               `json:"user_denied"`
	TimedOut        int               `json:"timed_out"`
	TrustedPatterns int               `json:"trusted_patterns"`
	DeniedPatterns  int               `json:"denied_patterns"`
	ByRiskLevel     map[RiskLevel]int `json:"by_risk_level"`
	ByCategory      map[string]int    `json:"by_category"`
	TopCommands     []CommandStat     `json:"top_commands"`
	AvgResponseTime float64           `json:"avg_response_time_ms"`
}

ApprovalStats 审批统计.

type CommandPattern

type CommandPattern struct {
	Pattern     string    `json:"pattern"`
	PatternHash string    `json:"pattern_hash"`
	Action      string    `json:"action"` // approved, denied
	Count       int       `json:"count"`
	RiskLevel   RiskLevel `json:"risk_level"`
	LastSeen    time.Time `json:"last_seen"`
	SessionIDs  []string  `json:"session_ids"`
	Trusted     bool      `json:"trusted"`
}

CommandPattern represents a learned command pattern.

type CommandStat added in v0.4.10

type CommandStat struct {
	Pattern   string    `json:"pattern"`
	Count     int       `json:"count"`
	Approved  int       `json:"approved"`
	Denied    int       `json:"denied"`
	RiskLevel RiskLevel `json:"risk_level"`
	LastSeen  time.Time `json:"last_seen"`
}

CommandStat 单个命令的审批统计.

type Manager

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

Manager handles command approvals with history, session learning, and web callbacks.

func NewManager

func NewManager(config *ApprovalConfig) (*Manager, error)

NewManager creates a new approval manager.

func (*Manager) AddToWhitelist

func (m *Manager) AddToWhitelist(pattern string) error

AddToWhitelist adds a command pattern to whitelist.

func (*Manager) Approve

func (m *Manager) Approve(req *ApprovalRequest) error

Approve records a user approval decision.

func (*Manager) CLIConfirm

func (m *Manager) CLIConfirm(req *ApprovalRequest) (bool, error)

CLIConfirm prompts user for confirmation in terminal.

func (*Manager) CleanupExpired added in v0.4.10

func (m *Manager) CleanupExpired()

CleanupExpired removes expired pending approvals.

func (*Manager) ClearHistory added in v0.4.10

func (m *Manager) ClearHistory(olderThan time.Duration)

ClearHistory removes approval records older than the given duration. Also cleans up stale session contexts and patterns that no longer have history entries.

func (*Manager) ConfigCommand

func (m *Manager) ConfigCommand() *cobra.Command

ConfigCommand returns CLI commands for approval management.

func (*Manager) Deny

func (m *Manager) Deny(req *ApprovalRequest) error

Deny records a user denial decision.

func (*Manager) GetConfig added in v0.4.10

func (m *Manager) GetConfig() *ApprovalConfig

GetConfig returns the current approval configuration.

func (*Manager) GetDeniedCommands

func (m *Manager) GetDeniedCommands() []*CommandPattern

GetDeniedCommands returns denied command patterns.

func (*Manager) GetHistory added in v0.4.10

func (m *Manager) GetHistory(limit int, offset int) []*ApprovalRecord

GetHistory returns approval history with pagination.

func (*Manager) GetPendingApprovals added in v0.4.10

func (m *Manager) GetPendingApprovals() []*PendingApproval

GetPendingApprovals returns all pending web approvals.

func (*Manager) GetStats added in v0.4.10

func (m *Manager) GetStats() *ApprovalStats

GetStats returns aggregated approval statistics with caching. The cache is invalidated when history changes (RecordDecision, ClearHistory).

func (*Manager) GetTrustedCommands

func (m *Manager) GetTrustedCommands() []*CommandPattern

GetTrustedCommands returns all trusted command patterns.

func (*Manager) GetWhitelist added in v0.4.10

func (m *Manager) GetWhitelist() []string

GetWhitelist returns all whitelisted patterns.

func (*Manager) HistoryLen added in v0.4.12

func (m *Manager) HistoryLen() int

HistoryLen returns the total number of history records.

func (*Manager) NotifyApproval

func (m *Manager) NotifyApproval(result *ApprovalResult, req *ApprovalRequest)

NotifyApproval notifies all callbacks of an approval result.

func (*Manager) PendingWebApproval added in v0.4.10

func (m *Manager) PendingWebApproval(req *ApprovalRequest) (*ApprovalResult, error)

PendingWebApproval creates a pending approval that waits for web resolution.

func (*Manager) RecordDecision added in v0.4.10

func (m *Manager) RecordDecision(req *ApprovalRequest, result string, duration int64)

RecordDecision records a specific approval decision to history (public API).

func (*Manager) RegisterCallback

func (m *Manager) RegisterCallback(cb ApprovalCallback)

RegisterCallback registers an approval callback.

func (*Manager) RemoveFromWhitelist

func (m *Manager) RemoveFromWhitelist(pattern string) error

RemoveFromWhitelist removes a pattern from whitelist.

func (*Manager) RequestApproval

func (m *Manager) RequestApproval(req *ApprovalRequest) (*ApprovalResult, error)

RequestApproval asks for approval of a command.

func (*Manager) ResolveWebApproval added in v0.4.10

func (m *Manager) ResolveWebApproval(id string, approved bool, reason string)

ResolveWebApproval resolves a pending web approval.

func (*Manager) SaveConfig added in v0.4.10

func (m *Manager) SaveConfig() error

SaveConfig is a no-op; config is persisted via the main config file.

func (*Manager) SetStrategy added in v0.4.10

func (m *Manager) SetStrategy(s Strategy)

SetStrategy updates the approval strategy (in-memory only; caller must persist to main config).

func (*Manager) SyncWithMemory

func (m *Manager) SyncWithMemory() error

SyncWithMemory syncs patterns with memory store.

type ParsedCommand added in v0.4.10

type ParsedCommand struct {
	Binary        string            // 命令二进制名 (如 "npm", "git")
	SubCommand    string            // 子命令 (如 "install", "push")
	Flags         map[string]string // 标志参数
	Args          []string          // 位置参数
	RawArgs       string            // 原始参数字符串
	HasPipe       bool              // 是否包含管道
	HasChain      bool              // 是否包含链式操作 (&&, ||, ;)
	PipeSegments  []string          // 管道分段
	ChainSegments []string          // 链式分段
}

ParsedCommand represents a parsed command structure.

type PatternMatchResult

type PatternMatchResult struct {
	Matched   bool
	Pattern   string
	Variables map[string]string
}

PatternMatchResult contains the result of a pattern match.

type PendingApproval added in v0.4.10

type PendingApproval struct {
	ID        string
	Request   *ApprovalRequest
	Result    chan *ApprovalResult
	CreatedAt time.Time
	ExpiresAt time.Time
}

PendingApproval 待Web审批的请求.

type RiskAssessment added in v0.4.10

type RiskAssessment struct {
	Level         RiskLevel // 最终风险等级
	Category      string    // "file_destruct", "network", "privilege_esc", "data_access", "system", "package_mgmt"
	Factors       []string  // 具体风险因素
	BypassAttempt bool      // 检测到绕过尝试
	BypassType    string    // 绕过类型 (encoding, variable, path_traversal)
	Score         float64   // 0-100 风险评分
}

RiskAssessment 包含详细的风险评估结果.

type RiskLevel

type RiskLevel int

RiskLevel represents the danger level of a command.

const (
	RiskLow      RiskLevel = 1
	RiskMedium   RiskLevel = 2
	RiskHigh     RiskLevel = 3
	RiskCritical RiskLevel = 4
)

func (RiskLevel) MarshalJSON added in v0.4.12

func (r RiskLevel) MarshalJSON() ([]byte, error)

MarshalJSON serializes RiskLevel as a string.

func (RiskLevel) String added in v0.4.10

func (r RiskLevel) String() string

String returns a human-readable label for the risk level.

func (*RiskLevel) UnmarshalJSON added in v0.4.12

func (r *RiskLevel) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes RiskLevel from a string or number.

type SessionApprovalContext added in v0.4.10

type SessionApprovalContext struct {
	SessionID    string
	RecentCmds   []string    // 最近执行的命令(归一化后)
	ApprovedHash map[int]int // riskLevel -> 同类批准次数
	CreatedAt    time.Time
}

SessionApprovalContext 会话级审批上下文,用于会话内学习.

type Strategy

type Strategy string

Strategy defines how commands are approved.

const (
	StrategyManual      Strategy = "manual"
	StrategyAutoApprove Strategy = "auto"
	StrategySmart       Strategy = "smart"
	StrategyWhitelist   Strategy = "whitelist"
)

type WebApprovalCallback added in v0.4.10

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

WebApprovalCallback Web端审批回调.

Jump to

Keyboard shortcuts

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