security

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var PIIPatternRegistry = []PIIPattern{

	{
		Type:        PIIEmail,
		Description: "Email address",
		Regex:       regexp.MustCompile(`\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b`),
	},

	{
		Type:        PIIChinesePhone,
		Description: "Chinese mobile phone number",
		Regex:       regexp.MustCompile(`\b1[3-9]\d{9}\b`),
		Validator:   validateChinesePhone,
	},

	{
		Type:        PIIPhone,
		Description: "US phone number",
		Regex:       regexp.MustCompile(`\b(?:\+?1[-.\s]?)?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})\b`),
	},

	{
		Type:        PIICreditCard,
		Description: "Credit card number",
		Regex:       regexp.MustCompile(`\b(?:4[0-9]{3}[-\s]?[0-9]{4}[-\s]?[0-9]{4}[-\s]?[0-9]{4}|5[1-5][0-9]{2}[-\s]?[0-9]{4}[-\s]?[0-9]{4}[-\s]?[0-9]{4}|3[47][0-9]{2}[-\s]?[0-9]{6}[-\s]?[0-9]{5})\b`),
		Validator:   validateLuhn,
	},

	{
		Type:        PIISSNus,
		Description: "US Social Security Number",
		Regex:       regexp.MustCompile(`\b\d{3}-?\d{2}-?\d{4}\b`),
		Validator:   validateSSN,
	},

	{
		Type:        PIIChineseID,
		Description: "Chinese ID card number",
		Regex:       regexp.MustCompile(`\b[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]\b`),
		Validator:   validateChineseID,
	},

	{
		Type:        PIIIPAddress,
		Description: "IPv4 address",
		Regex:       regexp.MustCompile(`\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b`),
	},

	{
		Type:        PIIPassport,
		Description: "Passport number (generic)",
		Regex:       regexp.MustCompile(`\b[A-Z]{1,2}[0-9]{6,9}\b`),
	},

	{
		Type:        PIIDateOfBirth,
		Description: "Date (potential date of birth)",
		Regex:       regexp.MustCompile(`\b(19|20)\d{2}[-/](0[1-9]|1[0-2])[-/](0[1-9]|[12]\d|3[01])\b`),
	},
}

PIIPatternRegistry PII 模式注册表。

Functions

func AddCustomPattern

func AddCustomPattern(pattern PIIPattern)

AddCustomPattern 添加自定义 PII 模式。

Types

type AccessCache added in v0.12.0

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

AccessCache 访问缓存

type AccessControlConfig added in v0.12.0

type AccessControlConfig struct {
	// 会话配置
	SessionTimeout     time.Duration `json:"session_timeout"`
	MaxSessionsPerUser int           `json:"max_sessions_per_user"`
	EnableSessionCache bool          `json:"enable_session_cache"`

	// 权限配置
	EnablePermissionCache  bool          `json:"enable_permission_cache"`
	PermissionCacheTimeout time.Duration `json:"permission_cache_timeout"`

	// 审计配置
	EnableAudit         bool       `json:"enable_audit"`
	AuditLevel          AuditLevel `json:"audit_level"`
	LoginFailureLockout bool       `json:"login_failure_lockout"`
	MaxFailedAttempts   int        `json:"max_failed_attempts"`

	// 安全配置
	PasswordPolicy   *PasswordPolicy   `json:"password_policy"`
	MFAPolicy        *MFAPolicy        `json:"mfa_policy"`
	IPLockdownPolicy *IPLockdownPolicy `json:"ip_lockdown_policy"`
}

AccessControlConfig 访问控制配置

type AccessController added in v0.12.0

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

AccessController 访问控制器

func NewAccessController added in v0.12.0

func NewAccessController(config *AccessControlConfig, auditLog AuditLog) *AccessController

NewAccessController 创建访问控制器

func (*AccessController) AssignRole added in v0.12.0

func (ac *AccessController) AssignRole(userID, roleID string) error

AssignRole 为用户分配角色

func (*AccessController) CheckPermission added in v0.12.0

func (ac *AccessController) CheckPermission(userID, resource, action string, context map[string]any) (*AccessDecision, error)

CheckPermission 检查用户权限

func (*AccessController) CreateSession added in v0.12.0

func (ac *AccessController) CreateSession(userID, ipAddress, userAgent string) (*Session, error)

CreateSession 创建会话

func (*AccessController) CreateUser added in v0.12.0

func (ac *AccessController) CreateUser(user *User) error

CreateUser 创建用户

func (*AccessController) DeleteSession added in v0.12.0

func (ac *AccessController) DeleteSession(sessionID string) error

DeleteSession 删除会话

func (*AccessController) DeleteUser added in v0.12.0

func (ac *AccessController) DeleteUser(userID string) error

DeleteUser 删除用户

func (*AccessController) GetSession added in v0.12.0

func (ac *AccessController) GetSession(sessionID string) (*Session, error)

GetSession 获取会话

func (*AccessController) GetUser added in v0.12.0

func (ac *AccessController) GetUser(userID string) (*User, error)

GetUser 获取用户

func (*AccessController) RevokeRole added in v0.12.0

func (ac *AccessController) RevokeRole(userID, roleID string) error

RevokeRole 撤销用户角色

func (*AccessController) UpdateUser added in v0.12.0

func (ac *AccessController) UpdateUser(user *User) error

UpdateUser 更新用户

type AccessDecision added in v0.12.0

type AccessDecision struct {
	Allowed      bool           `json:"allowed"`
	Effect       PolicyEffect   `json:"effect"`
	Reason       string         `json:"reason"`
	Policies     []string       `json:"policies"`    // 影响决策的策略ID
	Roles        []string       `json:"roles"`       // 相关角色
	Permissions  []string       `json:"permissions"` // 相关权限
	CacheHit     bool           `json:"cache_hit"`
	DecisionTime time.Duration  `json:"decision_time"`
	EvaluatedAt  time.Time      `json:"evaluated_at"`
	Context      map[string]any `json:"context"`
}

AccessDecision 访问决策

type AccessEventStats added in v0.12.0

type AccessEventStats struct {
	TotalAccessChecks int64 `json:"total_access_checks"`
	AccessGranted     int64 `json:"access_granted"`
	AccessDenied      int64 `json:"access_denied"`
	Unauthorized      int64 `json:"unauthorized"`
	Forbidden         int64 `json:"forbidden"`
}

AccessEventStats 访问事件统计

type AccessPolicy added in v0.12.0

type AccessPolicy struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Type        PolicyType        `json:"type"`       // 策略类型
	Effect      PolicyEffect      `json:"effect"`     // 策略效果
	Principal   string            `json:"principal"`  // 主体
	Resource    string            `json:"resource"`   // 资源
	Action      string            `json:"action"`     // 操作
	Conditions  []PolicyCondition `json:"conditions"` // 策略条件
	Priority    int               `json:"priority"`   // 优先级
	Enabled     bool              `json:"enabled"`
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
}

AccessPolicy 访问策略

type AccessRequest added in v0.12.0

type AccessRequest struct {
	UserID      string         `json:"user_id"`
	Username    string         `json:"username"`
	Resource    string         `json:"resource"`
	Action      string         `json:"action"`
	Context     map[string]any `json:"context"`
	IPAddress   string         `json:"ip_address"`
	UserAgent   string         `json:"user_agent"`
	SessionID   string         `json:"session_id"`
	RequestTime time.Time      `json:"request_time"`
}

AccessRequest 访问请求

type ActionStat added in v0.12.0

type ActionStat struct {
	Action     string `json:"action"`
	EventCount int64  `json:"event_count"`
}

ActionStat 操作统计

type AdaptiveStrategy

type AdaptiveStrategy struct {
	LowStrategy    RedactionStrategy
	MediumStrategy RedactionStrategy
	HighStrategy   RedactionStrategy
}

AdaptiveStrategy 自适应策略(根据敏感度选择策略)。

func NewAdaptiveStrategy

func NewAdaptiveStrategy() *AdaptiveStrategy

NewAdaptiveStrategy 创建自适应策略。

func (*AdaptiveStrategy) Name

func (s *AdaptiveStrategy) Name() string

Name 返回策略名称。

func (*AdaptiveStrategy) Redact

func (s *AdaptiveStrategy) Redact(match PIIMatch) string

Redact 根据敏感度选择策略。

type AlertType added in v0.12.0

type AlertType string

AlertType 警报类型

const (
	AlertTypeSuspiciousLogin     AlertType = "suspicious_login"
	AlertTypeBruteForceAttack    AlertType = "brute_force_attack"
	AlertTypePrivilegeEscalation AlertType = "privilege_escalation"
	AlertTypeDataAccessAnomaly   AlertType = "data_access_anomaly"
	AlertTypeUnauthorizedAccess  AlertType = "unauthorized_access"
)

type AuditCategory added in v0.12.0

type AuditCategory string

AuditCategory 审计类别

const (
	AuditCategoryAuthentication AuditCategory = "authentication" // 认证
	AuditCategoryAuthorization  AuditCategory = "authorization"  // 授权
	AuditCategoryAccess         AuditCategory = "access"         // 访问
	AuditCategoryConfiguration  AuditCategory = "configuration"  // 配置
	AuditCategorySecurity       AuditCategory = "security"       // 安全
	AuditCategorySystem         AuditCategory = "system"         // 系统
	AuditCategoryData           AuditCategory = "data"           // 数据
	AuditCategoryNetwork        AuditCategory = "network"        // 网络
)

type AuditConfiguration added in v0.12.0

type AuditConfiguration struct {
	// 存储配置
	StorageType   StorageType   `json:"storage_type"`
	StoragePath   string        `json:"storage_path,omitempty"`
	MaxFileSize   int64         `json:"max_file_size"`
	MaxFileAge    time.Duration `json:"max_file_age"`
	Compression   bool          `json:"compression"`
	Encryption    bool          `json:"encryption"`
	EncryptionKey string        `json:"encryption_key,omitempty"`

	// 缓存配置
	EnableCache  bool          `json:"enable_cache"`
	CacheSize    int           `json:"cache_size"`
	CacheTimeout time.Duration `json:"cache_timeout"`

	// 索引配置
	EnableIndexing bool     `json:"enable_indexing"`
	IndexFields    []string `json:"index_fields"`

	// 性能配置
	WorkerPoolSize int           `json:"worker_pool_size"`
	BatchSize      int           `json:"batch_size"`
	FlushInterval  time.Duration `json:"flush_interval"`

	// 保留策略
	RetentionPolicy *RetentionPolicy `json:"retention_policy"`

	// 实时监控
	EnableRealTime  bool           `json:"enable_real_time"`
	AlertThresholds map[string]int `json:"alert_thresholds"`

	// 安全配置
	EnableSignature bool   `json:"enable_signature"`
	SignatureKey    string `json:"signature_key,omitempty"`
	EnableHash      bool   `json:"enable_hash"`
	HashAlgorithm   string `json:"hash_algorithm,omitempty"`
}

AuditConfiguration 审计配置

type AuditEvent added in v0.12.0

type AuditEvent struct {
	ID         string         `json:"id"`
	Type       AuditType      `json:"type"`
	Timestamp  time.Time      `json:"timestamp"`
	Severity   AuditSeverity  `json:"severity"`
	Category   AuditCategory  `json:"category"`
	UserID     string         `json:"user_id,omitempty"`
	Username   string         `json:"username,omitempty"`
	AgentID    string         `json:"agent_id,omitempty"`
	SessionID  string         `json:"session_id,omitempty"`
	Resource   string         `json:"resource,omitempty"`
	Action     string         `json:"action,omitempty"`
	ObjectID   string         `json:"object_id,omitempty"`
	ObjectType string         `json:"object_type,omitempty"`
	IPAddress  string         `json:"ip_address,omitempty"`
	UserAgent  string         `json:"user_agent,omitempty"`
	Location   string         `json:"location,omitempty"`
	Result     AuditResult    `json:"result,omitempty"`
	Message    string         `json:"message"`
	Details    string         `json:"details,omitempty"`
	Duration   time.Duration  `json:"duration,omitempty"`
	RequestID  string         `json:"request_id,omitempty"`
	TraceID    string         `json:"trace_id,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
	RiskScore  float64        `json:"risk_score,omitempty"`
	Tags       []string       `json:"tags,omitempty"`
}

AuditEvent 审计事件

type AuditFilters added in v0.12.0

type AuditFilters struct {
	TimeRange  *TimeRange      `json:"time_range,omitempty"`
	Types      []AuditType     `json:"types,omitempty"`
	Users      []string        `json:"users,omitempty"`
	Resources  []string        `json:"resources,omitempty"`
	Severities []AuditSeverity `json:"severities,omitempty"`
}

AuditFilters 审计过滤条件

type AuditLevel added in v0.12.0

type AuditLevel string

AuditLevel 审计级别

const (
	AuditLevelNone   AuditLevel = "none"   // 无审计
	AuditLevelBasic  AuditLevel = "basic"  // 基础审计
	AuditLevelDetail AuditLevel = "detail" // 详细审计
	AuditLevelFull   AuditLevel = "full"   // 完整审计
)

type AuditLog added in v0.12.0

type AuditLog interface {
	// 基础操作
	LogEvent(event AuditEvent) error
	LogEventAsync(event AuditEvent) error
	LogEvents(events []AuditEvent) error

	// 查询操作
	QueryEvents(ctx context.Context, query *AuditQuery) (*AuditResult, error)
	GetEvent(eventID string) (*AuditEvent, error)
	GetEventsByUser(userID string, limit int) ([]*AuditEvent, error)
	GetEventsByType(eventType AuditType, limit int) ([]*AuditEvent, error)
	GetEventsByTimeRange(start, end time.Time, limit int) ([]*AuditEvent, error)

	// 统计操作
	GetStatistics(ctx context.Context, filters *AuditFilters) (*AuditStatistics, error)
	GetEventSummary(timeRange TimeRange) (*EventSummary, error)

	// 管理操作
	ArchiveEvents(ctx context.Context, before time.Time) (int64, error)
	PurgeEvents(ctx context.Context, before time.Time) (int64, error)
	ExportEvents(ctx context.Context, query *AuditQuery, format ExportFormat) ([]byte, error)

	// 配置和状态
	GetConfiguration() *AuditConfiguration
	UpdateConfiguration(config *AuditConfiguration) error
	GetStatus() *AuditLogStatus
	Close() error
}

AuditLog 审计日志接口

type AuditLogStatus added in v0.12.0

type AuditLogStatus struct {
	Status           string         `json:"status"`
	Version          string         `json:"version"`
	Uptime           time.Duration  `json:"uptime"`
	TotalEvents      int64          `json:"total_events"`
	EventsPerSecond  float64        `json:"events_per_second"`
	StorageSize      int64          `json:"storage_size"`
	LastEventTime    time.Time      `json:"last_event_time"`
	ErrorCount       int64          `json:"error_count"`
	LastError        string         `json:"last_error,omitempty"`
	WorkerPoolStatus map[string]any `json:"worker_pool_status"`
	MemoryUsage      map[string]any `json:"memory_usage"`
}

AuditLogStatus 审计日志状态

type AuditQuery added in v0.12.0

type AuditQuery struct {
	// 时间范围
	TimeRange *TimeRange `json:"time_range,omitempty"`

	// 过滤条件
	Types      []AuditType         `json:"types,omitempty"`
	Severities []AuditSeverity     `json:"severities,omitempty"`
	Categories []AuditCategory     `json:"categories,omitempty"`
	Users      []string            `json:"users,omitempty"`
	Resources  []string            `json:"resources,omitempty"`
	Actions    []string            `json:"actions,omitempty"`
	Results    []AuditResultStatus `json:"results,omitempty"`

	// 文本搜索
	SearchText string `json:"search_text,omitempty"`

	// 分页和排序
	Limit     int    `json:"limit"`
	Offset    int    `json:"offset"`
	OrderBy   string `json:"order_by"`   // 排序字段
	OrderDesc bool   `json:"order_desc"` // 是否降序

	// 元数据过滤
	MetadataFilters map[string]any `json:"metadata_filters,omitempty"`

	// 风险评分范围
	RiskScoreMin *float64 `json:"risk_score_min,omitempty"`
	RiskScoreMax *float64 `json:"risk_score_max,omitempty"`
}

AuditQuery 审计查询

type AuditResult added in v0.12.0

type AuditResult struct {
	Events    []*AuditEvent `json:"events"`
	Total     int64         `json:"total"`
	Offset    int           `json:"offset"`
	Limit     int           `json:"limit"`
	HasMore   bool          `json:"has_more"`
	QueryTime time.Duration `json:"query_time"`
}

AuditResult 审计查询结果

type AuditResultStatus added in v0.12.0

type AuditResultStatus string

AuditResultStatus 审计结果状态

const (
	AuditResultSuccess AuditResultStatus = "success" // 成功
	AuditResultFailure AuditResultStatus = "failure" // 失败
	AuditResultError   AuditResultStatus = "error"   // 错误
	AuditResultPartial AuditResultStatus = "partial" // 部分
)

type AuditSeverity added in v0.12.0

type AuditSeverity string

AuditSeverity 审计严重级别

const (
	AuditSeverityInfo     AuditSeverity = "info"     // 信息
	AuditSeverityLow      AuditSeverity = "low"      // 低风险
	AuditSeverityMedium   AuditSeverity = "medium"   // 中等风险
	AuditSeverityHigh     AuditSeverity = "high"     // 高风险
	AuditSeverityCritical AuditSeverity = "critical" // 严重
)

type AuditStatistics added in v0.12.0

type AuditStatistics struct {
	TimeRange      TimeRange           `json:"time_range"`
	TotalEvents    int64               `json:"total_events"`
	EventsByType   map[AuditType]int64 `json:"events_by_type"`
	EventsByUser   map[string]int64    `json:"events_by_user"`
	EventsByHour   map[int]int64       `json:"events_by_hour"` // 小时统计
	EventsByDay    map[string]int64    `json:"events_by_day"`  // 日期统计
	TopUsers       []UserStat          `json:"top_users"`
	TopResources   []ResourceStat      `json:"top_resources"`
	TopActions     []ActionStat        `json:"top_actions"`
	SecurityEvents SecurityEventStats  `json:"security_events"`
	AccessEvents   AccessEventStats    `json:"access_events"`
	GeneratedAt    time.Time           `json:"generated_at"`
}

AuditStatistics 审计统计

type AuditType added in v0.12.0

type AuditType string

AuditType 审计类型

const (
	// 用户相关审计事件
	AuditTypeUserCreated  AuditType = "user_created"
	AuditTypeUserUpdated  AuditType = "user_updated"
	AuditTypeUserDeleted  AuditType = "user_deleted"
	AuditTypeUserLogin    AuditType = "user_login"
	AuditTypeUserLogout   AuditType = "user_logout"
	AuditTypeUserLocked   AuditType = "user_locked"
	AuditTypeUserUnlocked AuditType = "user_unlocked"

	// 角色和权限相关审计事件
	AuditTypeRoleCreated       AuditType = "role_created"
	AuditTypeRoleUpdated       AuditType = "role_updated"
	AuditTypeRoleDeleted       AuditType = "role_deleted"
	AuditTypePermissionCreated AuditType = "permission_created"
	AuditTypePermissionUpdated AuditType = "permission_updated"
	AuditTypePermissionDeleted AuditType = "permission_deleted"
	AuditTypeRoleAssigned      AuditType = "role_assigned"
	AuditTypeRoleRevoked       AuditType = "role_revoked"

	// 会话相关审计事件
	AuditTypeSessionCreated AuditType = "session_created"
	AuditTypeSessionUpdated AuditType = "session_updated"
	AuditTypeSessionDeleted AuditType = "session_deleted"
	AuditTypeSessionExpired AuditType = "session_expired"

	// 访问相关审计事件
	AuditTypeAccessChecked AuditType = "access_checked"
	AuditTypeAccessGranted AuditType = "access_granted"
	AuditTypeAccessDenied  AuditType = "access_denied"

	// 策略相关审计事件
	AuditTypePolicyCreated AuditType = "policy_created"
	AuditTypePolicyUpdated AuditType = "policy_updated"
	AuditTypePolicyDeleted AuditType = "policy_deleted"
	AuditTypeUnauthorized  AuditType = "unauthorized"
	AuditTypeForbidden     AuditType = "forbidden"

	// 安全相关审计事件
	AuditTypeSecurityAlert      AuditType = "security_alert"
	AuditTypeSecurityViolation  AuditType = "security_violation"
	AuditTypeSuspiciousActivity AuditType = "suspicious_activity"
	AuditTypeAttackDetected     AuditType = "attack_detected"
	AuditTypeDataBreach         AuditType = "data_breach"

	// 系统相关审计事件
	AuditTypeSystemStarted        AuditType = "system_started"
	AuditTypeSystemShutdown       AuditType = "system_shutdown"
	AuditTypeConfigurationChanged AuditType = "configuration_changed"
	AuditTypeError                AuditType = "error"
)

type BasicPolicyEngine added in v0.12.0

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

BasicPolicyEngine 基础策略引擎实现

func NewBasicPolicyEngine added in v0.12.0

func NewBasicPolicyEngine(config *EngineConfig, auditLog AuditLog) *BasicPolicyEngine

NewBasicPolicyEngine 创建基础策略引擎

func (*BasicPolicyEngine) AddPolicy added in v0.12.0

func (bpe *BasicPolicyEngine) AddPolicy(policy *SecurityPolicy) error

AddPolicy 添加策略

func (*BasicPolicyEngine) DeletePolicy added in v0.12.0

func (bpe *BasicPolicyEngine) DeletePolicy(policyID string) error

DeletePolicy 删除策略

func (*BasicPolicyEngine) Evaluate added in v0.12.0

func (bpe *BasicPolicyEngine) Evaluate(request *PolicyRequest) (*PolicyEvaluation, error)

Evaluate 评估策略

func (*BasicPolicyEngine) GetPolicy added in v0.12.0

func (bpe *BasicPolicyEngine) GetPolicy(policyID string) (*SecurityPolicy, error)

GetPolicy 获取策略

func (*BasicPolicyEngine) ListPolicies added in v0.12.0

func (bpe *BasicPolicyEngine) ListPolicies(filters map[string]any) ([]*SecurityPolicy, error)

ListPolicies 列出策略

func (*BasicPolicyEngine) UpdatePolicy added in v0.12.0

func (bpe *BasicPolicyEngine) UpdatePolicy(policy *SecurityPolicy) error

UpdatePolicy 更新策略

type CacheEntry added in v0.12.0

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

CacheEntry 缓存条目

type ChallengeInfo added in v0.12.0

type ChallengeInfo struct {
	Type        string         `json:"type"` // CAPTCHA, MFA, 知识问答等
	Duration    time.Duration  `json:"duration"`
	MaxAttempts int            `json:"max_attempts"`
	Parameters  map[string]any `json:"parameters"`
}

ChallengeInfo 挑战信息

type CompositePIIDetector

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

CompositePIIDetector 组合多个检测器。

func NewCompositePIIDetector

func NewCompositePIIDetector(detectors ...PIIDetector) *CompositePIIDetector

NewCompositePIIDetector 创建组合检测器。

func (*CompositePIIDetector) ContainsPII

func (d *CompositePIIDetector) ContainsPII(ctx context.Context, text string) (bool, error)

ContainsPII 检查是否包含 PII。

func (*CompositePIIDetector) Detect

func (d *CompositePIIDetector) Detect(ctx context.Context, text string) ([]PIIMatch, error)

Detect 使用所有检测器检测 PII。

func (*CompositePIIDetector) DetectTypes

func (d *CompositePIIDetector) DetectTypes(ctx context.Context, text string, types ...PIIType) ([]PIIMatch, error)

DetectTypes 检测指定类型的 PII。

type CompositeRedactor added in v0.12.0

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

CompositeRedactor 组合脱敏器

func NewCompositeRedactor added in v0.12.0

func NewCompositeRedactor(redactors ...ContentRedactor) *CompositeRedactor

NewCompositeRedactor 创建组合脱敏器

func (*CompositeRedactor) AddRedactor added in v0.12.0

func (c *CompositeRedactor) AddRedactor(redactor ContentRedactor)

AddRedactor 添加脱敏器

func (*CompositeRedactor) Redact added in v0.12.0

func (c *CompositeRedactor) Redact(text string) string

Redact 使用所有脱敏器进行脱敏

type ConditionLogic added in v0.12.0

type ConditionLogic string

ConditionLogic 条件逻辑

const (
	ConditionLogicAND ConditionLogic = "and" // AND逻辑
	ConditionLogicOR  ConditionLogic = "or"  // OR逻辑
	ConditionLogicNOT ConditionLogic = "not" // NOT逻辑
)

type ConditionOperator added in v0.12.0

type ConditionOperator string

ConditionOperator 条件操作符

const (
	ConditionOperatorExists      ConditionOperator = "exists"    // 存在
	ConditionOperatorNotExists   ConditionOperator = "notexists" // 不存在
	ConditionOperatorEquals      ConditionOperator = "eq"        // 等于
	ConditionOperatorNotEquals   ConditionOperator = "ne"        // 不等于
	ConditionOperatorGreaterThan ConditionOperator = "gt"        // 大于
	ConditionOperatorLessThan    ConditionOperator = "lt"        // 小于
	ConditionOperatorContains    ConditionOperator = "contains"  // 包含
	ConditionOperatorMatches     ConditionOperator = "matches"   // 匹配
)

type ConditionType added in v0.12.0

type ConditionType string

ConditionType 条件类型

const (
	ConditionTypeStatic   ConditionType = "static"   // 静态条件
	ConditionTypeDynamic  ConditionType = "dynamic"  // 动态条件
	ConditionTypeContext  ConditionType = "context"  // 上下文条件
	ConditionTypeTime     ConditionType = "time"     // 时间条件
	ConditionTypeLocation ConditionType = "location" // 位置条件
	ConditionTypeRisk     ConditionType = "risk"     // 风险条件
)

type ConditionalPIIConfig

type ConditionalPIIConfig struct {
	Detector  PIIDetector
	Strategy  RedactionStrategy
	Condition func(context.Context, *middleware.ModelRequest) bool // 判断是否需要脱敏
	Priority  int
}

ConditionalPIIConfig 条件 PII 中间件配置。

type ConditionalPIIMiddleware

type ConditionalPIIMiddleware struct {
	*middleware.BaseMiddleware
	// contains filtered or unexported fields
}

ConditionalPIIMiddleware 条件 PII 脱敏中间件。 根据上下文条件决定是否脱敏。

func NewConditionalPIIMiddleware

func NewConditionalPIIMiddleware(cfg ConditionalPIIConfig) *ConditionalPIIMiddleware

NewConditionalPIIMiddleware 创建条件 PII 中间件。

func (*ConditionalPIIMiddleware) WrapModelCall

WrapModelCall 包装模型调用。

type ContentRedactor added in v0.12.0

type ContentRedactor interface {
	Redact(text string) string
}

ContentRedactor 接口定义了内容脱敏的方法

type EngineConfig added in v0.12.0

type EngineConfig struct {
	EnableCaching     bool          `json:"enable_caching"`
	CacheTimeout      time.Duration `json:"cache_timeout"`
	EnableMetrics     bool          `json:"enable_metrics"`
	EnableAudit       bool          `json:"enable_audit"`
	MaxConcurrentEval int           `json:"max_concurrent_eval"`
	DefaultAction     PolicyAction  `json:"default_action"`
}

EngineConfig 引擎配置

type EngineStatus added in v0.12.0

type EngineStatus struct {
	Status            string         `json:"status"`
	Version           string         `json:"version"`
	Uptime            time.Duration  `json:"uptime"`
	PolicyCount       int            `json:"policy_count"`
	ActivePolicyCount int            `json:"active_policy_count"`
	TotalEvaluations  int64          `json:"total_evaluations"`
	AverageLatency    time.Duration  `json:"average_latency"`
	ErrorRate         float64        `json:"error_rate"`
	LastReload        time.Time      `json:"last_reload"`
	MemoryUsage       map[string]any `json:"memory_usage"`
	CPUUsage          map[string]any `json:"cpu_usage"`
}

EngineStatus 引擎状态

type EnvironmentConstraints added in v0.12.0

type EnvironmentConstraints struct {
	AllowedIPs       []string `json:"allowed_ips,omitempty"`
	BlockedIPs       []string `json:"blocked_ips,omitempty"`
	AllowedCountries []string `json:"allowed_countries,omitempty"`
	BlockedCountries []string `json:"blocked_countries,omitempty"`
	AllowedRegions   []string `json:"allowed_regions,omitempty"`
	BlockedRegions   []string `json:"blocked_regions,omitempty"`
	RequiredEnv      []string `json:"required_env,omitempty"`
	BlockedEnv       []string `json:"blocked_env,omitempty"`
	SecurityLevel    string   `json:"security_level,omitempty"`
}

EnvironmentConstraints 环境约束

type EventSummary added in v0.12.0

type EventSummary struct {
	TimeRange       TimeRange       `json:"time_range"`
	TotalEvents     int64           `json:"total_events"`
	KeyMetrics      map[string]any  `json:"key_metrics"`
	Trends          []TrendData     `json:"trends"`
	Alerts          []SecurityAlert `json:"alerts"`
	Recommendations []string        `json:"recommendations"`
}

EventSummary 事件摘要

type ExportFormat added in v0.12.0

type ExportFormat string

ExportFormat 导出格式

const (
	ExportFormatJSON ExportFormat = "json" // JSON格式
	ExportFormatCSV  ExportFormat = "csv"  // CSV格式
	ExportFormatXML  ExportFormat = "xml"  // XML格式
	ExportFormatPDF  ExportFormat = "pdf"  // PDF格式
)

type HashStrategy

type HashStrategy struct {
	ShowPrefix   bool   // 是否显示哈希前缀
	PrefixLength int    // 哈希前缀长度
	Salt         string // 盐值(用于增强安全性)
}

HashStrategy 哈希策略(单向加密)。 例如:13812345678 -> [HASH:a3f5...]

func NewHashStrategy

func NewHashStrategy() *HashStrategy

NewHashStrategy 创建哈希策略。

func (*HashStrategy) Name

func (s *HashStrategy) Name() string

Name 返回策略名称。

func (*HashStrategy) Redact

func (s *HashStrategy) Redact(match PIIMatch) string

Redact 执行哈希脱敏。

type IPLockdownPolicy added in v0.12.0

type IPLockdownPolicy struct {
	Enabled         bool     `json:"enabled"`
	AllowedIPs      []string `json:"allowed_ips"`
	BlockedIPs      []string `json:"blocked_ips"`
	TrustedNetworks []string `json:"trusted_networks"`
	RequireVPN      bool     `json:"require_vpn"`
}

IPLockdownPolicy IP锁定策略

type InMemoryAuditLog added in v0.12.0

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

InMemoryAuditLog 内存审计日志实现

func NewInMemoryAuditLog added in v0.12.0

func NewInMemoryAuditLog(config *AuditConfiguration) *InMemoryAuditLog

NewInMemoryAuditLog 创建内存审计日志

func (*InMemoryAuditLog) ArchiveEvents added in v0.12.0

func (al *InMemoryAuditLog) ArchiveEvents(ctx context.Context, before time.Time) (int64, error)

ArchiveEvents 归档事件

func (*InMemoryAuditLog) Close added in v0.12.0

func (al *InMemoryAuditLog) Close() error

Close 关闭审计日志

func (*InMemoryAuditLog) ExportEvents added in v0.12.0

func (al *InMemoryAuditLog) ExportEvents(ctx context.Context, query *AuditQuery, format ExportFormat) ([]byte, error)

ExportEvents 导出事件

func (*InMemoryAuditLog) GetConfiguration added in v0.12.0

func (al *InMemoryAuditLog) GetConfiguration() *AuditConfiguration

GetConfiguration 获取配置

func (*InMemoryAuditLog) GetEvent added in v0.12.0

func (al *InMemoryAuditLog) GetEvent(eventID string) (*AuditEvent, error)

GetEvent 获取事件

func (*InMemoryAuditLog) GetEventSummary added in v0.12.0

func (al *InMemoryAuditLog) GetEventSummary(timeRange TimeRange) (*EventSummary, error)

GetEventSummary 获取事件摘要

func (*InMemoryAuditLog) GetEventsByTimeRange added in v0.12.0

func (al *InMemoryAuditLog) GetEventsByTimeRange(start, end time.Time, limit int) ([]*AuditEvent, error)

GetEventsByTimeRange 根据时间范围获取事件

func (*InMemoryAuditLog) GetEventsByType added in v0.12.0

func (al *InMemoryAuditLog) GetEventsByType(eventType AuditType, limit int) ([]*AuditEvent, error)

GetEventsByType 根据类型获取事件

func (*InMemoryAuditLog) GetEventsByUser added in v0.12.0

func (al *InMemoryAuditLog) GetEventsByUser(userID string, limit int) ([]*AuditEvent, error)

GetEventsByUser 根据用户获取事件

func (*InMemoryAuditLog) GetStatistics added in v0.12.0

func (al *InMemoryAuditLog) GetStatistics(ctx context.Context, filters *AuditFilters) (*AuditStatistics, error)

GetStatistics 获取统计信息

func (*InMemoryAuditLog) GetStatus added in v0.12.0

func (al *InMemoryAuditLog) GetStatus() *AuditLogStatus

GetStatus 获取状态

func (*InMemoryAuditLog) LogEvent added in v0.12.0

func (al *InMemoryAuditLog) LogEvent(event AuditEvent) error

LogEvent 记录事件

func (*InMemoryAuditLog) LogEventAsync added in v0.12.0

func (al *InMemoryAuditLog) LogEventAsync(event AuditEvent) error

LogEventAsync 异步记录事件

func (*InMemoryAuditLog) LogEvents added in v0.12.0

func (al *InMemoryAuditLog) LogEvents(events []AuditEvent) error

LogEvents 批量记录事件

func (*InMemoryAuditLog) PurgeEvents added in v0.12.0

func (al *InMemoryAuditLog) PurgeEvents(ctx context.Context, before time.Time) (int64, error)

PurgeEvents 清理事件

func (*InMemoryAuditLog) QueryEvents added in v0.12.0

func (al *InMemoryAuditLog) QueryEvents(ctx context.Context, query *AuditQuery) (*AuditResult, error)

QueryEvents 查询事件

func (*InMemoryAuditLog) UpdateConfiguration added in v0.12.0

func (al *InMemoryAuditLog) UpdateConfiguration(config *AuditConfiguration) error

UpdateConfiguration 更新配置

type MFAMethod added in v0.12.0

type MFAMethod string

MFAMethod 多因素认证方法

const (
	MFAMethodTOTP      MFAMethod = "totp"      // 时间动态口令
	MFAMethodSMS       MFAMethod = "sms"       // 短信验证
	MFAMethodEmail     MFAMethod = "email"     // 邮件验证
	MFAMethodHardware  MFAMethod = "hardware"  // 硬件令牌
	MFAMethodBiometric MFAMethod = "biometric" // 生物识别
)

type MFAPolicy added in v0.12.0

type MFAPolicy struct {
	Enabled         bool        `json:"enabled"`
	RequiredRoles   []string    `json:"required_roles"`
	RequiredActions []string    `json:"required_actions"`
	Methods         []MFAMethod `json:"methods"`
	BackupMethods   []MFAMethod `json:"backup_methods"`
}

MFAPolicy 多因素认证策略

type MaskStrategy

type MaskStrategy struct {
	MaskChar      rune // 掩码字符(默认 '*')
	KeepPrefix    int  // 保留前缀长度
	KeepSuffix    int  // 保留后缀长度
	MinMaskLength int  // 最小掩码长度
}

MaskStrategy 掩码策略(部分掩码)。 例如:13812345678 -> 138****5678

func NewMaskStrategy

func NewMaskStrategy() *MaskStrategy

NewMaskStrategy 创建掩码策略。

func (*MaskStrategy) Name

func (s *MaskStrategy) Name() string

Name 返回策略名称。

func (*MaskStrategy) Redact

func (s *MaskStrategy) Redact(match PIIMatch) string

Redact 执行掩码脱敏。

type NoOpStrategy

type NoOpStrategy struct{}

NoOpStrategy 无操作策略(不脱敏,用于测试)。

func (*NoOpStrategy) Name

func (s *NoOpStrategy) Name() string

Name 返回策略名称。

func (*NoOpStrategy) Redact

func (s *NoOpStrategy) Redact(match PIIMatch) string

Redact 不进行脱敏。

type PIIContext

type PIIContext struct {
	// Language 文本语言(zh/en等)
	Language string

	// AllowedTypes 允许的 PII 类型(白名单)
	AllowedTypes []PIIType

	// IgnorePatterns 忽略的模式(如公司邮箱域名)
	IgnorePatterns []string

	// MinConfidence 最低置信度阈值
	MinConfidence float64
}

PIIContext PII 的上下文信息(用于更好的检测)。

type PIIDetectionResult

type PIIDetectionResult struct {
	Matches      []PIIMatch
	HasPII       bool
	PIITypes     []PIIType
	HighestRisk  PIISensitivityLevel
	TotalMatches int
}

PIIDetectionResult 检测结果汇总。

func AnalyzePII

func AnalyzePII(ctx context.Context, text string, detector PIIDetector) (*PIIDetectionResult, error)

AnalyzePII 分析文本中的 PII 并返回详细报告。

type PIIDetectionSummary

type PIIDetectionSummary struct {
	AgentID      string
	HasPII       bool
	TotalMatches int
	TypeCounts   map[PIIType]int
	HighestRisk  PIISensitivityLevel
}

PIIDetectionSummary PII 检测摘要。

type PIIDetector

type PIIDetector interface {
	// Detect 检测文本中的所有 PII。
	Detect(ctx context.Context, text string) ([]PIIMatch, error)

	// DetectTypes 检测指定类型的 PII。
	DetectTypes(ctx context.Context, text string, types ...PIIType) ([]PIIMatch, error)

	// ContainsPII 快速检查文本是否包含 PII。
	ContainsPII(ctx context.Context, text string) (bool, error)
}

PIIDetector PII 检测器接口。

type PIIMatch

type PIIMatch struct {
	Type       PIIType             // PII 类型
	Value      string              // 原始值
	Start      int                 // 起始位置
	End        int                 // 结束位置
	Confidence float64             // 置信度(0.0-1.0)
	Severity   PIISensitivityLevel // 敏感度级别
}

PIIMatch 表示一个 PII 匹配结果。

func FilterMatchesByContext

func FilterMatchesByContext(matches []PIIMatch, ctx *PIIContext) []PIIMatch

FilterMatchesByContext 根据上下文过滤匹配结果。

type PIIMiddlewareConfig

type PIIMiddlewareConfig struct {
	Detector       PIIDetector       // PII 检测器
	Strategy       RedactionStrategy // 脱敏策略
	EnableTracking bool              // 是否启用 PII 追踪
	Priority       int               // 中间件优先级(默认 200)
}

PIIMiddlewareConfig PII 中间件配置。

type PIIPattern

type PIIPattern struct {
	Type        PIIType
	Description string
	Regex       *regexp.Regexp
	Validator   func(string) bool // 可选的额外验证函数
}

PIIPattern 定义一个 PII 检测模式。

func GetPatternsByType

func GetPatternsByType(types ...PIIType) []PIIPattern

GetPatternsByType 按类型获取 PII 模式。

type PIIRedactionMiddleware

type PIIRedactionMiddleware struct {
	*middleware.BaseMiddleware
	// contains filtered or unexported fields
}

PIIRedactionMiddleware PII 脱敏中间件。 在消息发送到 LLM 前自动检测和脱敏 PII。

func NewDefaultPIIMiddleware

func NewDefaultPIIMiddleware() *PIIRedactionMiddleware

NewDefaultPIIMiddleware 创建默认配置的 PII 中间件。

func NewPIIRedactionMiddleware

func NewPIIRedactionMiddleware(cfg PIIMiddlewareConfig) *PIIRedactionMiddleware

NewPIIRedactionMiddleware 创建 PII 脱敏中间件。

func (*PIIRedactionMiddleware) ClearTracking

func (m *PIIRedactionMiddleware) ClearTracking(agentID string)

ClearTracking 清除 Agent 的追踪信息。

func (*PIIRedactionMiddleware) GetPIIMatches

func (m *PIIRedactionMiddleware) GetPIIMatches(agentID string) []PIIMatch

GetPIIMatches 获取 Agent 的 PII 匹配记录。

func (*PIIRedactionMiddleware) GetPIISummary

func (m *PIIRedactionMiddleware) GetPIISummary(agentID string) *PIIDetectionSummary

GetPIISummary 获取 PII 检测摘要。

func (*PIIRedactionMiddleware) OnAgentStop

func (m *PIIRedactionMiddleware) OnAgentStop(ctx context.Context, agentID string) error

OnAgentStop 在 Agent 停止时清除追踪信息。

func (*PIIRedactionMiddleware) WrapModelCall

WrapModelCall 包装模型调用,在发送前脱敏 PII。

type PIIRedactor added in v0.12.0

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

PIIRedactor PII脱敏器

func NewPIIRedactor added in v0.12.0

func NewPIIRedactor(detector PIIDetector) *PIIRedactor

NewPIIRedactor 创建PII脱敏器

func (*PIIRedactor) AddCustomPIIType added in v0.12.0

func (r *PIIRedactor) AddCustomPIIType(piiType PIIType, replacement string)

AddCustomPIIType 添加自定义PII类型

func (*PIIRedactor) AnalyzeAndRedact added in v0.12.0

func (r *PIIRedactor) AnalyzeAndRedact(text string) (*RedactionResult, string)

AnalyzeAndRedact 分析并脱敏,返回脱敏报告

func (*PIIRedactor) GetReplacement added in v0.12.0

func (r *PIIRedactor) GetReplacement(piiType PIIType) string

GetReplacement 获取特定PII类型的替换文本

func (*PIIRedactor) Redact added in v0.12.0

func (r *PIIRedactor) Redact(text string) string

Redact 脱敏文本中的PII信息

func (*PIIRedactor) RedactWithMasking added in v0.12.0

func (r *PIIRedactor) RedactWithMasking(text string, maskLength int) string

RedactWithMasking 使用掩码脱敏

func (*PIIRedactor) SetReplacement added in v0.12.0

func (r *PIIRedactor) SetReplacement(piiType PIIType, replacement string)

SetReplacement 设置特定PII类型的替换文本

type PIISensitivityLevel

type PIISensitivityLevel int

PIISensitivityLevel PII 敏感度级别。

const (
	SensitivityLow    PIISensitivityLevel = 1 // 低敏感(如邮箱)
	SensitivityMedium PIISensitivityLevel = 2 // 中等敏感(如电话号码)
	SensitivityHigh   PIISensitivityLevel = 3 // 高敏感(如身份证、信用卡)
)

func GetSensitivityLevel

func GetSensitivityLevel(piiType PIIType) PIISensitivityLevel

GetSensitivityLevel 返回 PII 类型的敏感度级别。

type PIIType

type PIIType string

PIIType 定义 PII 的类型。

const (
	PIIEmail        PIIType = "email"
	PIIPhone        PIIType = "phone"
	PIICreditCard   PIIType = "credit_card"
	PIISSNus        PIIType = "ssn_us"        // 美国社会安全号
	PIIChineseID    PIIType = "chinese_id"    // 中国身份证
	PIIChinesePhone PIIType = "chinese_phone" // 中国手机号
	PIIIPAddress    PIIType = "ip_address"
	PIIPassport     PIIType = "passport"
	PIIBankAccount  PIIType = "bank_account"
	PIIDateOfBirth  PIIType = "date_of_birth"
	PIIAddress      PIIType = "address"
	PIIName         PIIType = "name" // 需要 LLM 检测
	PIICustom       PIIType = "custom"
)

type PasswordPolicy added in v0.12.0

type PasswordPolicy struct {
	MinLength        int           `json:"min_length"`
	RequireUppercase bool          `json:"require_uppercase"`
	RequireLowercase bool          `json:"require_lowercase"`
	RequireNumbers   bool          `json:"require_numbers"`
	RequireSymbols   bool          `json:"require_symbols"`
	MaxAge           time.Duration `json:"max_age"`
	HistoryCount     int           `json:"history_count"`
	PreventReuse     bool          `json:"prevent_reuse"`
}

PasswordPolicy 密码策略

type Permission added in v0.12.0

type Permission struct {
	ID          string                `json:"id"`
	Name        string                `json:"name"`
	Description string                `json:"description"`
	Resource    string                `json:"resource"`   // 资源类型
	Action      string                `json:"action"`     // 操作类型
	Conditions  []PermissionCondition `json:"conditions"` // 权限条件
	Attributes  map[string]any        `json:"attributes"`
	Enabled     bool                  `json:"enabled"`
	CreatedAt   time.Time             `json:"created_at"`
	UpdatedAt   time.Time             `json:"updated_at"`
}

Permission 权限

type PermissionCondition added in v0.12.0

type PermissionCondition struct {
	Type        string `json:"type"`     // 条件类型
	Field       string `json:"field"`    // 字段名
	Operator    string `json:"operator"` // 操作符
	Value       any    `json:"value"`    // 条件值
	Description string `json:"description"`
}

PermissionCondition 权限条件

type PolicyAction added in v0.12.0

type PolicyAction string

PolicyAction 策略动作

const (
	ActionAllow      PolicyAction = "allow"      // 允许
	ActionDeny       PolicyAction = "deny"       // 拒绝
	ActionWarn       PolicyAction = "warn"       // 警告
	ActionAudit      PolicyAction = "audit"      // 审计
	ActionQuarantine PolicyAction = "quarantine" // 隔离
	ActionBlock      PolicyAction = "block"      // 阻塞
	ActionRedirect   PolicyAction = "redirect"   // 重定向
	ActionTransform  PolicyAction = "transform"  // 转换
	ActionChallenge  PolicyAction = "challenge"  // 挑战
	ActionStepUp     PolicyAction = "stepup"     // 升级认证
)

type PolicyAnalysis added in v0.12.0

type PolicyAnalysis struct {
	PolicyID         string                 `json:"policy_id"`
	Period           TimeRange              `json:"period"`
	TotalRequests    int64                  `json:"total_requests"`
	AllowedRequests  int64                  `json:"allowed_requests"`
	DeniedRequests   int64                  `json:"denied_requests"`
	AverageScore     float64                `json:"average_score"`
	RiskDistribution map[RiskLevel]int64    `json:"risk_distribution"`
	ActionStats      map[PolicyAction]int64 `json:"action_stats"`
	TopViolators     []string               `json:"top_violators"`
	Recommendations  []string               `json:"recommendations"`
}

PolicyAnalysis 策略分析结果

type PolicyCondition added in v0.12.0

type PolicyCondition struct {
	ID          string            `json:"id"`
	Type        ConditionType     `json:"type"`
	Field       string            `json:"field"`
	Operator    ConditionOperator `json:"operator"`
	Value       any               `json:"value"`
	Logic       ConditionLogic    `json:"logic"` // AND, OR, NOT
	Description string            `json:"description"`
	Enabled     bool              `json:"enabled"`
	Metadata    map[string]any    `json:"metadata"`
}

PolicyCondition 策略条件

type PolicyEffect added in v0.12.0

type PolicyEffect string

PolicyEffect 策略效果

const (
	PolicyEffectAllow PolicyEffect = "Allow" // 允许
	PolicyEffectDeny  PolicyEffect = "Deny"  // 拒绝
)

type PolicyEngine added in v0.12.0

type PolicyEngine interface {
	// 策略管理
	AddPolicy(policy *SecurityPolicy) error
	UpdatePolicy(policy *SecurityPolicy) error
	DeletePolicy(policyID string) error
	GetPolicy(policyID string) (*SecurityPolicy, error)
	ListPolicies(filters map[string]any) ([]*SecurityPolicy, error)
	EnablePolicy(policyID string) error
	DisablePolicy(policyID string) error

	// 策略评估
	Evaluate(request *PolicyRequest) (*PolicyEvaluation, error)
	EvaluateBatch(requests []*PolicyRequest) ([]*PolicyEvaluation, error)
	EvaluateRealTime(request *PolicyRequest) (*PolicyEvaluation, error)

	// 规则管理
	AddRule(policyID string, rule *PolicyRule) error
	RemoveRule(policyID string, ruleID string) error
	UpdateRule(policyID string, rule *PolicyRule) error

	// 条件管理
	AddCondition(policyID string, condition *PolicyCondition) error
	RemoveCondition(policyID string, conditionID string) error
	UpdateCondition(policyID string, condition *PolicyCondition) error

	// 分析和报告
	AnalyzePolicy(policyID string, timeRange TimeRange) (*PolicyAnalysis, error)
	GenerateReport(reportType ReportType, filters map[string]any) (*PolicyReport, error)

	// 配置和状态
	GetEngineStatus() *EngineStatus
	ReloadPolicies() error
	BackupPolicies() ([]byte, error)
	RestorePolicies(data []byte) error
}

PolicyEngine 策略引擎接口

type PolicyEvaluation added in v0.12.0

type PolicyEvaluation struct {
	PolicyID            string          `json:"policy_id"`
	PolicyName          string          `json:"policy_name"`
	Allowed             bool            `json:"allowed"`
	Action              PolicyAction    `json:"action"`
	Reason              string          `json:"reason"`
	Score               float64         `json:"score"` // 风险评分 0-100
	RiskLevel           RiskLevel       `json:"risk_level"`
	Duration            time.Duration   `json:"duration"`
	MatchedRules        []string        `json:"matched_rules"`
	TriggeredConditions []string        `json:"triggered_conditions"`
	Response            *PolicyResponse `json:"response,omitempty"`
	Metadata            map[string]any  `json:"metadata"`
	EvaluatedAt         time.Time       `json:"evaluated_at"`
}

PolicyEvaluation 策略评估结果

type PolicyReport added in v0.12.0

type PolicyReport struct {
	ID          string         `json:"id"`
	Type        ReportType     `json:"type"`
	Title       string         `json:"title"`
	Period      TimeRange      `json:"period"`
	GeneratedAt time.Time      `json:"generated_at"`
	GeneratedBy string         `json:"generated_by"`
	Content     map[string]any `json:"content"`
	Format      ReportFormat   `json:"format"`
}

PolicyReport 策略报告

type PolicyRequest added in v0.12.0

type PolicyRequest struct {
	RequestID   string         `json:"request_id"`
	UserID      string         `json:"user_id,omitempty"`
	AgentID     string         `json:"agent_id,omitempty"`
	Action      string         `json:"action"`
	Resource    string         `json:"resource"`
	Context     map[string]any `json:"context"`
	IPAddress   string         `json:"ip_address,omitempty"`
	UserAgent   string         `json:"user_agent,omitempty"`
	Timestamp   time.Time      `json:"timestamp"`
	Environment string         `json:"environment,omitempty"`
	Location    string         `json:"location,omitempty"`
	Metadata    map[string]any `json:"metadata"`
}

PolicyRequest 策略请求

type PolicyResponse added in v0.12.0

type PolicyResponse struct {
	Message     string            `json:"message"`
	Code        int               `json:"code"`
	Headers     map[string]string `json:"headers,omitempty"`
	RedirectURL string            `json:"redirect_url,omitempty"`
	Challenge   *ChallengeInfo    `json:"challenge,omitempty"`
	Transform   *TransformInfo    `json:"transform,omitempty"`
	Metadata    map[string]any    `json:"metadata"`
}

PolicyResponse 策略响应

type PolicyRule added in v0.12.0

type PolicyRule struct {
	ID          string         `json:"id"`
	Type        RuleType       `json:"type"`
	Field       string         `json:"field"`
	Operator    RuleOperator   `json:"operator"`
	Value       any            `json:"value"`
	Description string         `json:"description"`
	Enabled     bool           `json:"enabled"`
	Priority    int            `json:"priority"`
	Metadata    map[string]any `json:"metadata"`
}

PolicyRule 策略规则

type PolicyScope added in v0.12.0

type PolicyScope string

PolicyScope 策略作用域

const (
	ScopeGlobal    PolicyScope = "global"    // 全局
	ScopeAgent     PolicyScope = "agent"     // Agent级别
	ScopeWorkflow  PolicyScope = "workflow"  // 工作流级别
	ScopeSession   PolicyScope = "session"   // 会话级别
	ScopeResource  PolicyScope = "resource"  // 资源级别
	ScopeOperation PolicyScope = "operation" // 操作级别
)

type PolicyTarget added in v0.12.0

type PolicyTarget string

PolicyTarget 策略目标

const (
	TargetAll     PolicyTarget = "all"     // 所有目标
	TargetUser    PolicyTarget = "user"    // 用户
	TargetAgent   PolicyTarget = "agent"   // Agent
	TargetSystem  PolicyTarget = "system"  // 系统
	TargetNetwork PolicyTarget = "network" // 网络
	TargetData    PolicyTarget = "data"    // 数据
	TargetAPI     PolicyTarget = "api"     // API
)

type PolicyType added in v0.12.0

type PolicyType string

PolicyType 策略类型

const (
	PolicyTypeAllow PolicyType = "allow" // 允许策略
	PolicyTypeDeny  PolicyType = "deny"  // 拒绝策略
)

type RedactionReport

type RedactionReport struct {
	OriginalLength     int             // 原始文本长度
	RedactedLength     int             // 脱敏后文本长度
	TotalMatches       int             // 总匹配数
	RedactedCharacters int             // 脱敏字符数
	MatchesByType      map[PIIType]int // 每种类型的匹配数
}

RedactionReport 脱敏报告。

type RedactionResult added in v0.12.0

type RedactionResult struct {
	OriginalLength int             `json:"original_length"`
	RedactedLength int             `json:"redacted_length"`
	PIIFound       bool            `json:"pii_found"`
	MatchedTypes   map[PIIType]int `json:"matched_types"`
	TotalMatches   int             `json:"total_matches"`
	Matches        []PIIMatch      `json:"matches"`
	Error          string          `json:"error,omitempty"`
}

RedactionResult 脱敏结果报告

func (*RedactionResult) GetSummary added in v0.12.0

func (r *RedactionResult) GetSummary() string

GetSummary 获取脱敏摘要

type RedactionStrategy

type RedactionStrategy interface {
	// Redact 脱敏单个 PII 值。
	Redact(match PIIMatch) string

	// Name 返回策略名称。
	Name() string
}

RedactionStrategy 脱敏策略接口。

type Redactor

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

Redactor PII 脱敏器。

func NewRedactor

func NewRedactor(detector PIIDetector, strategy RedactionStrategy) *Redactor

NewRedactor 创建脱敏器。

func (*Redactor) Redact

func (r *Redactor) Redact(ctx context.Context, text string) (string, error)

Redact 脱敏文本中的所有 PII。

func (*Redactor) RedactWithReport

func (r *Redactor) RedactWithReport(ctx context.Context, text string) (string, *RedactionReport, error)

RedactWithReport 脱敏文本并返回详细报告。

type RegexPIIDetector

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

RegexPIIDetector 基于正则表达式的 PII 检测器。

func NewRegexPIIDetector

func NewRegexPIIDetector() *RegexPIIDetector

NewRegexPIIDetector 创建正则表达式 PII 检测器。

func NewRegexPIIDetectorWithTypes

func NewRegexPIIDetectorWithTypes(types ...PIIType) *RegexPIIDetector

NewRegexPIIDetectorWithTypes 创建检测特定类型的 PII 检测器。

func (*RegexPIIDetector) ContainsPII

func (d *RegexPIIDetector) ContainsPII(ctx context.Context, text string) (bool, error)

ContainsPII 快速检查文本是否包含 PII。

func (*RegexPIIDetector) Detect

func (d *RegexPIIDetector) Detect(ctx context.Context, text string) ([]PIIMatch, error)

Detect 检测文本中的所有 PII。

func (*RegexPIIDetector) DetectTypes

func (d *RegexPIIDetector) DetectTypes(ctx context.Context, text string, types ...PIIType) ([]PIIMatch, error)

DetectTypes 检测指定类型的 PII。

type ReplaceStrategy

type ReplaceStrategy struct {
	UseTypeLabel bool               // 是否使用类型标签(如 [PHONE])
	CustomLabels map[PIIType]string // 自定义标签
}

ReplaceStrategy 替换策略(替换为占位符)。 例如:13812345678 -> [PHONE]

func NewReplaceStrategy

func NewReplaceStrategy() *ReplaceStrategy

NewReplaceStrategy 创建替换策略。

func (*ReplaceStrategy) Name

func (s *ReplaceStrategy) Name() string

Name 返回策略名称。

func (*ReplaceStrategy) Redact

func (s *ReplaceStrategy) Redact(match PIIMatch) string

Redact 执行替换脱敏。

type ReportFormat added in v0.12.0

type ReportFormat string

ReportFormat 报告格式

const (
	ReportFormatJSON ReportFormat = "json" // JSON格式
	ReportFormatCSV  ReportFormat = "csv"  // CSV格式
	ReportFormatPDF  ReportFormat = "pdf"  // PDF格式
	ReportFormatHTML ReportFormat = "html" // HTML格式
)

type ReportType added in v0.12.0

type ReportType string

ReportType 报告类型

const (
	ReportTypeSummary    ReportType = "summary"    // 摘要报告
	ReportTypeDetail     ReportType = "detail"     // 详细报告
	ReportTypeViolation  ReportType = "violation"  // 违规报告
	ReportTypeTrend      ReportType = "trend"      // 趋势报告
	ReportTypeCompliance ReportType = "compliance" // 合规报告
)

type ResourceStat added in v0.12.0

type ResourceStat struct {
	Resource   string `json:"resource"`
	EventCount int64  `json:"event_count"`
}

ResourceStat 资源统计

type RetentionPolicy added in v0.12.0

type RetentionPolicy struct {
	EnableAutoArchive bool          `json:"enable_auto_archive"`
	ArchiveAfter      time.Duration `json:"archive_after"`
	EnableAutoPurge   bool          `json:"enable_auto_purge"`
	PurgeAfter        time.Duration `json:"purge_after"`
	MinRetention      time.Duration `json:"min_retention"`
	MaxRetention      time.Duration `json:"max_retention"`
}

RetentionPolicy 保留策略

type RiskLevel added in v0.12.0

type RiskLevel string

RiskLevel 风险级别

const (
	RiskLevelLow      RiskLevel = "low"      // 低风险
	RiskLevelMedium   RiskLevel = "medium"   // 中等风险
	RiskLevelHigh     RiskLevel = "high"     // 高风险
	RiskLevelCritical RiskLevel = "critical" // 严重风险
)

type Role added in v0.12.0

type Role struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Permissions []string       `json:"permissions"`
	Parents     []string       `json:"parents"` // 父角色,继承权限
	Attributes  map[string]any `json:"attributes"`
	Enabled     bool           `json:"enabled"`
	Priority    int            `json:"priority"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	CreatedBy   string         `json:"created_by"`
	UpdatedBy   string         `json:"updated_by"`
}

Role 角色

type RuleOperator added in v0.12.0

type RuleOperator string

RuleOperator 规则操作符

const (
	OperatorEquals      RuleOperator = "eq"         // 等于
	OperatorNotEquals   RuleOperator = "ne"         // 不等于
	OperatorGreaterThan RuleOperator = "gt"         // 大于
	OperatorGreaterOrEq RuleOperator = "gte"        // 大于等于
	OperatorLessThan    RuleOperator = "lt"         // 小于
	OperatorLessOrEq    RuleOperator = "lte"        // 小于等于
	OperatorContains    RuleOperator = "contains"   // 包含
	OperatorNotContains RuleOperator = "ncontains"  // 不包含
	OperatorIn          RuleOperator = "in"         // 在列表中
	OperatorNotIn       RuleOperator = "nin"        // 不在列表中
	OperatorMatches     RuleOperator = "matches"    // 匹配正则
	OperatorNotMatches  RuleOperator = "nmatches"   // 不匹配正则
	OperatorStartsWith  RuleOperator = "startswith" // 以...开始
	OperatorEndsWith    RuleOperator = "endswith"   // 以...结束
)

type RuleType added in v0.12.0

type RuleType string

RuleType 规则类型

const (
	RuleTypeBasic  RuleType = "basic"  // 基础规则
	RuleTypeRegex  RuleType = "regex"  // 正则表达式规则
	RuleTypeScript RuleType = "script" // 脚本规则
	RuleTypeML     RuleType = "ml"     // 机器学习规则
	RuleTypeCustom RuleType = "custom" // 自定义规则
)

type SecurityAlert added in v0.12.0

type SecurityAlert struct {
	ID          string         `json:"id"`
	Type        AlertType      `json:"type"`
	Severity    AuditSeverity  `json:"severity"`
	Message     string         `json:"message"`
	Description string         `json:"description"`
	Events      []string       `json:"events"` // 相关事件ID
	DetectedAt  time.Time      `json:"detected_at"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

SecurityAlert 安全警报

type SecurityEventStats added in v0.12.0

type SecurityEventStats struct {
	TotalAlerts     int64 `json:"total_alerts"`
	TotalViolations int64 `json:"total_violations"`
	TotalAttacks    int64 `json:"total_attacks"`
	HighRiskEvents  int64 `json:"high_risk_events"`
	CriticalEvents  int64 `json:"critical_events"`
}

SecurityEventStats 安全事件统计

type SecurityPolicy added in v0.12.0

type SecurityPolicy struct {
	// 基本信息
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Version     string `json:"version"`
	Enabled     bool   `json:"enabled"`
	Priority    int    `json:"priority"` // 优先级,数值越高优先级越高

	// 作用域
	Scope     PolicyScope  `json:"scope"`
	Target    PolicyTarget `json:"target"`
	Resources []string     `json:"resources"` // 资源列表

	// 规则
	Rules      []PolicyRule      `json:"rules"`
	Conditions []PolicyCondition `json:"conditions"`

	// 动作
	Allow   []string `json:"allow"`   // 允许的动作
	Deny    []string `json:"deny"`    // 拒绝的动作
	Require []string `json:"require"` // 必需的条件

	// 时间限制
	TimeConstraints *TimeConstraints `json:"time_constraints,omitempty"`

	// 环境限制
	EnvironmentConstraints *EnvironmentConstraints `json:"environment_constraints,omitempty"`

	// 处理方式
	Action   PolicyAction   `json:"action"`
	Response PolicyResponse `json:"response"`

	// 元数据
	Tags     []string       `json:"tags"`
	Metadata map[string]any `json:"metadata"`

	// 审计
	AuditEnabled bool       `json:"audit_enabled"`
	AuditLevel   AuditLevel `json:"audit_level"`

	// 创建和更新信息
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedBy string    `json:"created_by"`
	UpdatedBy string    `json:"updated_by"`
}

SecurityPolicy 安全策略

type Session added in v0.12.0

type Session struct {
	ID           string         `json:"id"`
	UserID       string         `json:"user_id"`
	Username     string         `json:"username"`
	Roles        []string       `json:"roles"`
	Permissions  []string       `json:"permissions"`
	IPAddress    string         `json:"ip_address"`
	UserAgent    string         `json:"user_agent"`
	Attributes   map[string]any `json:"attributes"`
	Status       SessionStatus  `json:"status"`
	CreatedAt    time.Time      `json:"created_at"`
	LastActivity time.Time      `json:"last_activity"`
	ExpiresAt    time.Time      `json:"expires_at"`
}

Session 会话

type SessionStatus added in v0.12.0

type SessionStatus string

SessionStatus 会话状态

const (
	SessionStatusActive   SessionStatus = "active"   // 活跃
	SessionStatusExpired  SessionStatus = "expired"  // 已过期
	SessionStatusRevoked  SessionStatus = "revoked"  // 已撤销
	SessionStatusInactive SessionStatus = "inactive" // 非活跃
)

type StorageType added in v0.12.0

type StorageType string

StorageType 存储类型

const (
	StorageTypeMemory   StorageType = "memory"   // 内存存储
	StorageTypeFile     StorageType = "file"     // 文件存储
	StorageTypeDatabase StorageType = "database" // 数据库存储
	StorageTypeElastic  StorageType = "elastic"  // Elasticsearch
)

type TimeConstraints added in v0.12.0

type TimeConstraints struct {
	StartDate *time.Time     `json:"start_date,omitempty"`
	EndDate   *time.Time     `json:"end_date,omitempty"`
	StartTime string         `json:"start_time,omitempty"` // HH:MM格式
	EndTime   string         `json:"end_time,omitempty"`   // HH:MM格式
	TimeZone  string         `json:"timezone,omitempty"`
	Weekdays  []int          `json:"weekdays,omitempty"` // 0-6,0为周日
	Duration  *time.Duration `json:"duration,omitempty"` // 最大持续时间
}

TimeConstraints 时间约束

type TimeRange added in v0.12.0

type TimeRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

TimeRange 时间范围

type TransformInfo added in v0.12.0

type TransformInfo struct {
	Type       string         `json:"type"` // 数据脱敏、格式转换等
	Parameters map[string]any `json:"parameters"`
}

TransformInfo 转换信息

type TrendData added in v0.12.0

type TrendData struct {
	Timestamp time.Time `json:"timestamp"`
	Value     int64     `json:"value"`
	Label     string    `json:"label,omitempty"`
}

TrendData 趋势数据

type User added in v0.12.0

type User struct {
	ID         string         `json:"id"`
	Username   string         `json:"username"`
	Email      string         `json:"email"`
	FullName   string         `json:"full_name"`
	Roles      []string       `json:"roles"`
	Attributes map[string]any `json:"attributes"`
	Status     UserStatus     `json:"status"`
	Enabled    bool           `json:"enabled"`
	LastLogin  *time.Time     `json:"last_login"`
	CreatedAt  time.Time      `json:"created_at"`
	UpdatedAt  time.Time      `json:"updated_at"`
}

User 用户

type UserStat added in v0.12.0

type UserStat struct {
	UserID       string    `json:"user_id"`
	Username     string    `json:"username"`
	EventCount   int64     `json:"event_count"`
	LastActivity time.Time `json:"last_activity"`
}

UserStat 用户统计

type UserStatus added in v0.12.0

type UserStatus string

UserStatus 用户状态

const (
	UserStatusActive    UserStatus = "active"    // 活跃
	UserStatusInactive  UserStatus = "inactive"  // 非活跃
	UserStatusSuspended UserStatus = "suspended" // 暂停
	UserStatusLocked    UserStatus = "locked"    // 锁定
)

Jump to

Keyboard shortcuts

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