Documentation
¶
Overview ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats ¶
Package prompt provides protection against prompt injection and other LLM-specific security threats
Index ¶
- type ActionType
- type AdvancedJailbreakDetector
- type AdvancedTemplateMonitor
- func (m *AdvancedTemplateMonitor) GetAlertHistory() []*Alert
- func (m *AdvancedTemplateMonitor) GetSessionStats(sessionID string) (*SessionStats, error)
- func (m *AdvancedTemplateMonitor) GetTemplateStats(templateID string) (*TemplateStats, error)
- func (m *AdvancedTemplateMonitor) GetUserStats(userID string) (*UserStats, error)
- func (m *AdvancedTemplateMonitor) MonitorTemplate(ctx context.Context, templateID string, templateName string, userID string, ...) error
- func (m *AdvancedTemplateMonitor) RegisterAlertHandler(name string, handler func(context.Context, *Alert) error)
- func (m *AdvancedTemplateMonitor) StartMonitoring(ctx context.Context) error
- func (m *AdvancedTemplateMonitor) StopMonitoring()
- type Alert
- type AlertManager
- type Anomaly
- type AnomalyDetector
- type ApprovalAction
- type ApprovalHandlerFunc
- type ApprovalLevel
- type ApprovalRequest
- type ApprovalStatus
- type ApprovalWorkflow
- func (w *ApprovalWorkflow) ApproveRequest(requestID string) bool
- func (w *ApprovalWorkflow) DenyRequest(requestID string) bool
- func (w *ApprovalWorkflow) GetPendingRequests() []*ApprovalRequest
- func (w *ApprovalWorkflow) GetRequestStatus(requestID string) (string, bool)
- func (w *ApprovalWorkflow) RequestApproval(ctx context.Context, result *ProtectionResult) (bool, *ProtectionResult, error)
- type ApprovalWorkflowConfig
- type AutoApprovalRule
- type BoundaryDefinition
- type ContentFilter
- type ContentFilterConfig
- type ContextBoundaryConfig
- type ContextBoundaryEnforcer
- type ContextHistoryEntry
- type CustomPattern
- type Detection
- type DetectionLocation
- type DetectionType
- type EmergingPattern
- type EnhancedApprovalConfig
- type EnhancedApprovalRequest
- type EnhancedApprovalWorkflow
- func (w *EnhancedApprovalWorkflow) AddApprovalLevel(name string, level ApprovalLevel)
- func (w *EnhancedApprovalWorkflow) AddAutoApprovalRule(rule AutoApprovalRule)
- func (w *EnhancedApprovalWorkflow) ApproveRequest(requestID string, approverID string, reason string) error
- func (w *EnhancedApprovalWorkflow) EnableAutoApproval(enabled bool)
- func (w *EnhancedApprovalWorkflow) GetApprovalHistory() []*EnhancedApprovalRequest
- func (w *EnhancedApprovalWorkflow) GetApprovalRequest(requestID string) (*EnhancedApprovalRequest, error)
- func (w *EnhancedApprovalWorkflow) GetPendingApprovals() []*EnhancedApprovalRequest
- func (w *EnhancedApprovalWorkflow) RegisterApprovalHandler(name string, handler ApprovalHandlerFunc)
- func (w *EnhancedApprovalWorkflow) RejectRequest(requestID string, approverID string, reason string) error
- func (w *EnhancedApprovalWorkflow) RequestApprovalEnhanced(ctx context.Context, result *ProtectionResult) (bool, *ProtectionResult, error)
- func (w *EnhancedApprovalWorkflow) SetApprovalThreshold(level string, threshold float64)
- func (w *EnhancedApprovalWorkflow) SetDefaultApprovalLevel(level string) error
- type EnhancedContentFilter
- func (cf *EnhancedContentFilter) Disable()
- func (cf *EnhancedContentFilter) Enable()
- func (cf *EnhancedContentFilter) FilterContent(ctx context.Context, content string) (*FilterResult, error)
- func (cf *EnhancedContentFilter) GetConfig() FilterConfig
- func (cf *EnhancedContentFilter) IsEnabled() bool
- func (cf *EnhancedContentFilter) UpdatePatterns(allowedPatterns, blockedPatterns []string) error
- type EnhancedContextBoundaryEnforcer
- func (e *EnhancedContextBoundaryEnforcer) EnableStrictMode(enabled bool)
- func (e *EnhancedContextBoundaryEnforcer) EnforceBoundariesEnhanced(ctx context.Context, prompt string) (string, *ProtectionResult, error)
- func (e *EnhancedContextBoundaryEnforcer) GetBoundaryViolations() map[string]int
- func (e *EnhancedContextBoundaryEnforcer) GetContextHistory() []*ContextHistoryEntry
- type EnhancedInjectionPatternLibrary
- func (l *EnhancedInjectionPatternLibrary) AddCustomPattern(pattern string, description string, creator string, categories []string) error
- func (l *EnhancedInjectionPatternLibrary) AddEmergingPattern(pattern string, description string, source string, examples []string, ...) error
- func (l *EnhancedInjectionPatternLibrary) DetectPatternsEnhanced(prompt string, result *ProtectionResult)
- func (l *EnhancedInjectionPatternLibrary) EnableCustomPattern(pattern string, enabled bool) error
- func (l *EnhancedInjectionPatternLibrary) GetCustomPatterns() []*CustomPattern
- func (l *EnhancedInjectionPatternLibrary) GetEmergingPatterns() []*EmergingPattern
- func (l *EnhancedInjectionPatternLibrary) GetPatternStats(pattern string) (*PatternStats, error)
- func (l *EnhancedInjectionPatternLibrary) GetPatternsByCategory(category string) ([]*InjectionPattern, error)
- func (l *EnhancedInjectionPatternLibrary) ValidateEmergingPattern(pattern string, validated bool) error
- type EnhancedInjectionReport
- type EnhancedProtectionConfig
- type EnhancedProtectionManager
- func (pm *EnhancedProtectionManager) AnalyzeReports(ctx context.Context) error
- func (pm *EnhancedProtectionManager) Close() error
- func (pm *EnhancedProtectionManager) EnableComponent(component string, enabled bool)
- func (pm *EnhancedProtectionManager) GetApprovalWorkflow() *EnhancedApprovalWorkflow
- func (pm *EnhancedProtectionManager) GetPatternLibrary() *EnhancedInjectionPatternLibrary
- func (pm *EnhancedProtectionManager) GetReportingSystem() *EnhancedReportingSystem
- func (pm *EnhancedProtectionManager) GetTemplateMonitor() *AdvancedTemplateMonitor
- func (pm *EnhancedProtectionManager) ProtectPromptEnhanced(ctx context.Context, prompt string, userID string, sessionID string, ...) (string, *ProtectionResult, error)
- func (pm *EnhancedProtectionManager) ProtectResponseEnhanced(ctx context.Context, response string, originalPrompt string, userID string, ...) (string, *ProtectionResult, error)
- func (pm *EnhancedProtectionManager) SetProtectionLevel(level ProtectionLevel)
- func (pm *EnhancedProtectionManager) StartMonitoring(ctx context.Context) error
- func (pm *EnhancedProtectionManager) StopMonitoring()
- type EnhancedReportingConfig
- type EnhancedReportingSystem
- func (r *EnhancedReportingSystem) AddReportingEndpoint(name string, endpoint string)
- func (r *EnhancedReportingSystem) AnalyzeReports(ctx context.Context) error
- func (r *EnhancedReportingSystem) CreateCustomReport(ctx context.Context, detectionType DetectionType, pattern string, ...) (*EnhancedInjectionReport, error)
- func (r *EnhancedReportingSystem) EnableAutomaticReporting(enabled bool)
- func (r *EnhancedReportingSystem) GetReport(reportID string) (*EnhancedInjectionReport, error)
- func (r *EnhancedReportingSystem) GetReports() []*EnhancedInjectionReport
- func (r *EnhancedReportingSystem) GetReportsByCategory(category string) []*EnhancedInjectionReport
- func (r *EnhancedReportingSystem) GetReportsByStatus(status ReportStatus) []*EnhancedInjectionReport
- func (r *EnhancedReportingSystem) RegisterReportHandler(name string, handler ReportHandlerFunc)
- func (r *EnhancedReportingSystem) ReportInjectionEnhanced(ctx context.Context, detections []*Detection, prompt string, response string) error
- func (r *EnhancedReportingSystem) SetReportingThreshold(threshold float64)
- func (r *EnhancedReportingSystem) ShareReport(ctx context.Context, reportID string, destination string) error
- func (r *EnhancedReportingSystem) VerifyReport(ctx context.Context, reportID string, verified bool, reason string) error
- type FilterConfig
- type FilterResult
- type InjectionPattern
- type InjectionPatternLibrary
- func (l *InjectionPatternLibrary) AddPattern(pattern *InjectionPattern) error
- func (l *InjectionPatternLibrary) DetectPatterns(prompt string, result *ProtectionResult)
- func (l *InjectionPatternLibrary) DisablePattern(id string)
- func (l *InjectionPatternLibrary) EnablePattern(id string)
- func (l *InjectionPatternLibrary) GetAllPatterns() []*InjectionPattern
- func (l *InjectionPatternLibrary) GetPattern(id string) *InjectionPattern
- func (l *InjectionPatternLibrary) GetPatternsByCategory(category PatternCategory) []*InjectionPattern
- func (l *InjectionPatternLibrary) LoadPatternsFromFile(filePath string) error
- func (l *InjectionPatternLibrary) RemovePattern(id string)
- func (l *InjectionPatternLibrary) SavePatternsToFile(filePath string) error
- type InjectionReport
- type JailbreakDetectionConfig
- type JailbreakDetector
- type MonitoringConfig
- type PatternCategory
- type PatternStats
- type PromptProtectionMiddleware
- type ProtectionConfig
- type ProtectionLevel
- type ProtectionManager
- type ProtectionResult
- type ReportHandlerFunc
- type ReportStatus
- type ReportingConfig
- type ReportingSystem
- func (r *ReportingSystem) Close() error
- func (r *ReportingSystem) GetReportByID(reportID string) *InjectionReport
- func (r *ReportingSystem) GetReports() []*InjectionReport
- func (r *ReportingSystem) GetReportsByType(detectionType DetectionType) []*InjectionReport
- func (r *ReportingSystem) ReportDetections(ctx context.Context, result *ProtectionResult)
- func (r *ReportingSystem) Start()
- func (r *ReportingSystem) Stop()
- type RoleDefinition
- type SessionStats
- type TemplateMonitor
- func (m *TemplateMonitor) GetAllPatternStats() []*TemplatePatternStats
- func (m *TemplateMonitor) GetPatternStats(pattern string) *TemplatePatternStats
- func (m *TemplateMonitor) MonitorPrompt(ctx context.Context, result *ProtectionResult)
- func (m *TemplateMonitor) Start(ctx context.Context)
- func (m *TemplateMonitor) Stop()
- type TemplatePatternStats
- type TemplateStats
- type UserStats
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ActionType ¶
type ActionType int
ActionType defines the type of action taken by the protection system
const ( // ActionNone indicates no action was taken ActionNone ActionType = iota // ActionModified indicates the prompt/response was modified ActionModified // ActionWarned indicates a warning was issued ActionWarned // ActionBlocked indicates the prompt/response was blocked ActionBlocked // ActionLogged indicates the prompt/response was logged ActionLogged // ActionReported indicates the prompt/response was reported ActionReported )
func (ActionType) String ¶ added in v0.8.0
func (a ActionType) String() string
String returns the string representation of ActionType
type AdvancedJailbreakDetector ¶
type AdvancedJailbreakDetector struct {
*JailbreakDetector
// contains filtered or unexported fields
}
AdvancedJailbreakDetector extends the JailbreakDetector with more sophisticated detection capabilities
func NewAdvancedJailbreakDetector ¶
func NewAdvancedJailbreakDetector(config *ProtectionConfig, patternLibrary *InjectionPatternLibrary) *AdvancedJailbreakDetector
NewAdvancedJailbreakDetector creates a new advanced jailbreak detector
func (*AdvancedJailbreakDetector) DetectAdvancedJailbreak ¶
func (d *AdvancedJailbreakDetector) DetectAdvancedJailbreak(ctx context.Context, prompt string) (*ProtectionResult, error)
type AdvancedTemplateMonitor ¶
type AdvancedTemplateMonitor struct {
// contains filtered or unexported fields
}
AdvancedTemplateMonitor provides real-time monitoring for unusual template patterns
func NewAdvancedTemplateMonitor ¶
func NewAdvancedTemplateMonitor(config *ProtectionConfig, patternLibrary *EnhancedInjectionPatternLibrary) *AdvancedTemplateMonitor
NewAdvancedTemplateMonitor creates a new advanced template monitor
func (*AdvancedTemplateMonitor) GetAlertHistory ¶
func (m *AdvancedTemplateMonitor) GetAlertHistory() []*Alert
GetAlertHistory gets the alert history
func (*AdvancedTemplateMonitor) GetSessionStats ¶
func (m *AdvancedTemplateMonitor) GetSessionStats(sessionID string) (*SessionStats, error)
GetSessionStats gets statistics for a session
func (*AdvancedTemplateMonitor) GetTemplateStats ¶
func (m *AdvancedTemplateMonitor) GetTemplateStats(templateID string) (*TemplateStats, error)
GetTemplateStats gets statistics for a template
func (*AdvancedTemplateMonitor) GetUserStats ¶
func (m *AdvancedTemplateMonitor) GetUserStats(userID string) (*UserStats, error)
GetUserStats gets statistics for a user
func (*AdvancedTemplateMonitor) MonitorTemplate ¶
func (m *AdvancedTemplateMonitor) MonitorTemplate(ctx context.Context, templateID string, templateName string, userID string, sessionID string, prompt string, result *ProtectionResult) error
MonitorTemplate monitors a template execution
func (*AdvancedTemplateMonitor) RegisterAlertHandler ¶
func (m *AdvancedTemplateMonitor) RegisterAlertHandler(name string, handler func(context.Context, *Alert) error)
RegisterAlertHandler registers a handler for alerts
func (*AdvancedTemplateMonitor) StartMonitoring ¶
func (m *AdvancedTemplateMonitor) StartMonitoring(ctx context.Context) error
StartMonitoring starts the template monitoring
func (*AdvancedTemplateMonitor) StopMonitoring ¶
func (m *AdvancedTemplateMonitor) StopMonitoring()
StopMonitoring stops the template monitoring
type Alert ¶
type Alert struct {
AlertID string `json:"alert_id"`
Timestamp time.Time `json:"timestamp"`
Severity string `json:"severity"`
Type string `json:"type"`
Message string `json:"message"`
TemplateID string `json:"template_id,omitempty"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
DetectionType DetectionType `json:"detection_type,omitempty"`
RiskScore float64 `json:"risk_score"`
AnomalyScore float64 `json:"anomaly_score"`
RelatedAlerts []string `json:"related_alerts,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Alert represents a monitoring alert
type AlertManager ¶
type AlertManager struct {
// contains filtered or unexported fields
}
AlertManager manages alerts for template monitoring
type Anomaly ¶
type Anomaly struct {
Type string `json:"type"`
Message string `json:"message"`
Score float64 `json:"score"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Anomaly represents a detected anomaly
type AnomalyDetector ¶
type AnomalyDetector struct {
// contains filtered or unexported fields
}
AnomalyDetector detects anomalies in template usage
type ApprovalAction ¶
type ApprovalAction struct {
ActionType string `json:"action_type"`
ActorID string `json:"actor_id"`
Timestamp time.Time `json:"timestamp"`
Reason string `json:"reason,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ApprovalAction defines an action taken on an approval request
type ApprovalHandlerFunc ¶
type ApprovalHandlerFunc func(context.Context, *EnhancedApprovalRequest) (bool, error)
ApprovalHandlerFunc defines a function that handles approval requests
type ApprovalLevel ¶
type ApprovalLevel struct {
Name string `json:"name"`
Description string `json:"description"`
RequiredApprovers int `json:"required_approvers"`
AllowedApprovers []string `json:"allowed_approvers,omitempty"`
MaxRiskScore float64 `json:"max_risk_score"`
ApprovalTimeout time.Duration `json:"approval_timeout"`
}
ApprovalLevel defines a level of approval
type ApprovalRequest ¶
type ApprovalRequest struct {
// OriginalPrompt is the original prompt
OriginalPrompt string `json:"original_prompt"`
// ProtectedPrompt is the protected prompt
ProtectedPrompt string `json:"protected_prompt"`
// Detections is a list of detections
Detections []*Detection `json:"detections"`
// RiskScore is the overall risk score (0.0-1.0)
RiskScore float64 `json:"risk_score"`
// RequestID is a unique identifier for the request
RequestID string `json:"request_id"`
// Timestamp is the time of the request
Timestamp time.Time `json:"timestamp"`
// Requester is the identifier of the requester
Requester string `json:"requester,omitempty"`
// Reason is the reason for the approval request
Reason string `json:"reason"`
// Metadata contains additional metadata about the request
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ApprovalRequest defines a request for approval
type ApprovalStatus ¶
type ApprovalStatus string
ApprovalStatus defines the status of an approval request
const ( // ApprovalStatusPending indicates the approval request is pending ApprovalStatusPending ApprovalStatus = "pending" // ApprovalStatusApproved indicates the approval request was approved ApprovalStatusApproved ApprovalStatus = "approved" // ApprovalStatusRejected indicates the approval request was rejected ApprovalStatusRejected ApprovalStatus = "rejected" // ApprovalStatusExpired indicates the approval request expired ApprovalStatusExpired ApprovalStatus = "expired" // ApprovalStatusCancelled indicates the approval request was cancelled ApprovalStatusCancelled ApprovalStatus = "cancelled" )
type ApprovalWorkflow ¶
type ApprovalWorkflow struct {
// contains filtered or unexported fields
}
ApprovalWorkflow manages approval workflows for high-risk operations
func NewApprovalWorkflow ¶
func NewApprovalWorkflow(config *ProtectionConfig) *ApprovalWorkflow
NewApprovalWorkflow creates a new approval workflow
func (*ApprovalWorkflow) ApproveRequest ¶
func (w *ApprovalWorkflow) ApproveRequest(requestID string) bool
ApproveRequest approves a pending request
func (*ApprovalWorkflow) DenyRequest ¶
func (w *ApprovalWorkflow) DenyRequest(requestID string) bool
DenyRequest denies a pending request
func (*ApprovalWorkflow) GetPendingRequests ¶
func (w *ApprovalWorkflow) GetPendingRequests() []*ApprovalRequest
GetPendingRequests gets all pending approval requests
func (*ApprovalWorkflow) GetRequestStatus ¶
func (w *ApprovalWorkflow) GetRequestStatus(requestID string) (string, bool)
GetRequestStatus gets the status of an approval request
func (*ApprovalWorkflow) RequestApproval ¶
func (w *ApprovalWorkflow) RequestApproval(ctx context.Context, result *ProtectionResult) (bool, *ProtectionResult, error)
RequestApproval requests approval for a high-risk operation
type ApprovalWorkflowConfig ¶
type ApprovalWorkflowConfig struct {
// ApprovalThreshold is the risk score threshold for requiring approval
ApprovalThreshold float64 `json:"approval_threshold"`
// ApprovalTimeout is the timeout for approval requests
ApprovalTimeout time.Duration `json:"approval_timeout"`
// EnableAutoApproval enables automatic approval based on rules
EnableAutoApproval bool `json:"enable_auto_approval"`
// AutoApprovalRules defines rules for automatic approval
AutoApprovalRules []string `json:"auto_approval_rules,omitempty"`
}
ApprovalWorkflowConfig defines the configuration for the approval workflow
type AutoApprovalRule ¶
type AutoApprovalRule struct {
Name string `json:"name"`
Description string `json:"description"`
MaxRiskScore float64 `json:"max_risk_score"`
AllowedDetectionTypes []DetectionType `json:"allowed_detection_types"`
DisallowedDetectionTypes []DetectionType `json:"disallowed_detection_types"`
RequiredMetadata map[string]interface{} `json:"required_metadata,omitempty"`
ApplicableUsers []string `json:"applicable_users,omitempty"`
Enabled bool `json:"enabled"`
}
AutoApprovalRule defines a rule for auto-approval
type BoundaryDefinition ¶
type BoundaryDefinition struct {
Name string `json:"name"`
AllowedCommands []string `json:"allowed_commands"`
ForbiddenCommands []string `json:"forbidden_commands"`
AllowedTopics []string `json:"allowed_topics"`
ForbiddenTopics []string `json:"forbidden_topics"`
SecurityLevel int `json:"security_level"`
BoundaryTokens []string `json:"boundary_tokens"`
}
BoundaryDefinition defines a context boundary
type ContentFilter ¶
type ContentFilter struct {
// contains filtered or unexported fields
}
ContentFilter filters content for prohibited or sensitive information
func NewContentFilter ¶
func NewContentFilter(config *ProtectionConfig) *ContentFilter
NewContentFilter creates a new content filter
func (*ContentFilter) FilterContent ¶
func (f *ContentFilter) FilterContent(ctx context.Context, content string, originalPrompt string) (string, *ProtectionResult, error)
FilterContent filters content for sensitive information and returns a ProtectionResult. The filtering process includes: 1. Detecting sensitive information like API keys and credentials 2. Detecting system information that should not be exposed 3. Masking or redacting detected sensitive content 4. Setting appropriate risk scores and actions based on detections
The returned ProtectionResult contains: - Filtered content with sensitive information masked - List of detections with details about what was found - Risk score indicating the severity of the detections - Action taken (e.g., filtered, blocked) based on configuration
type ContentFilterConfig ¶
type ContentFilterConfig struct {
// EnableProfanityFilter enables filtering of profanity
EnableProfanityFilter bool `json:"enable_profanity_filter"`
// EnablePIIFilter enables filtering of personally identifiable information
EnablePIIFilter bool `json:"enable_pii_filter"`
// EnableCodeFilter enables filtering of code
EnableCodeFilter bool `json:"enable_code_filter"`
// EnableURLFilter enables filtering of URLs
EnableURLFilter bool `json:"enable_url_filter"`
// CustomFilters defines custom content filters
CustomFilters map[string]string `json:"custom_filters,omitempty"`
// ReplacementChar is the character to use for replacements
ReplacementChar rune `json:"replacement_char"`
// FilterThreshold is the threshold for filtering (0.0-1.0)
FilterThreshold float64 `json:"filter_threshold"`
}
ContentFilterConfig defines the configuration for content filtering
type ContextBoundaryConfig ¶
type ContextBoundaryConfig struct {
// EnableTokenization enables tokenization of prompts
EnableTokenization bool `json:"enable_tokenization"`
// EnableSanitization enables sanitization of prompts
EnableSanitization bool `json:"enable_sanitization"`
// EnableNormalization enables normalization of prompts
EnableNormalization bool `json:"enable_normalization"`
// MaxPromptLength is the maximum allowed length for prompts
MaxPromptLength int `json:"max_prompt_length"`
// SanitizationLevel defines how aggressively to sanitize inputs (1-3)
SanitizationLevel int `json:"sanitization_level"`
}
ContextBoundaryConfig defines the configuration for context boundary enforcement
type ContextBoundaryEnforcer ¶
type ContextBoundaryEnforcer struct {
// contains filtered or unexported fields
}
ContextBoundaryEnforcer enforces context boundaries to prevent prompt injection
func NewContextBoundaryEnforcer ¶
func NewContextBoundaryEnforcer(config *ProtectionConfig) *ContextBoundaryEnforcer
NewContextBoundaryEnforcer creates a new context boundary enforcer
func (*ContextBoundaryEnforcer) EnforceBoundaries ¶
func (e *ContextBoundaryEnforcer) EnforceBoundaries(ctx context.Context, prompt string) (string, *ProtectionResult, error)
EnforceBoundaries enforces context boundaries on a prompt
type ContextHistoryEntry ¶
type ContextHistoryEntry struct {
Timestamp time.Time `json:"timestamp"`
OriginalPrompt string `json:"original_prompt"`
ModifiedPrompt string `json:"modified_prompt"`
Detections []*Detection `json:"detections"`
BoundaryViolations []string `json:"boundary_violations"`
ActionTaken ActionType `json:"action_taken"`
}
ContextHistoryEntry represents an entry in the context history
type CustomPattern ¶
type CustomPattern struct {
Pattern string `json:"pattern"`
Description string `json:"description"`
Creator string `json:"creator"`
CreationTime time.Time `json:"creation_time"`
Enabled bool `json:"enabled"`
Categories []string `json:"categories"`
}
CustomPattern represents a user-defined pattern
type Detection ¶
type Detection struct {
// Type is the type of detection
Type DetectionType `json:"type"`
// Confidence is the confidence level of the detection (0.0-1.0)
Confidence float64 `json:"confidence"`
// Description is a human-readable description of the detection
Description string `json:"description"`
// Location is the location of the detection in the prompt or response
Location *DetectionLocation `json:"location,omitempty"`
// Pattern is the pattern that triggered the detection
Pattern string `json:"pattern,omitempty"`
// Remediation is a suggested remediation for the detection
Remediation string `json:"remediation,omitempty"`
// Metadata contains additional metadata about the detection
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Detection defines a detection of a potential security issue
type DetectionLocation ¶
type DetectionLocation struct {
// Start is the starting index of the detection
Start int `json:"start"`
// End is the ending index of the detection
End int `json:"end"`
// Context is the surrounding context of the detection
Context string `json:"context,omitempty"`
}
DetectionLocation defines the location of a detection in a prompt or response
type DetectionType ¶
type DetectionType string
DetectionType defines the type of detection
const ( // DetectionTypeNone indicates no detection was made DetectionTypeNone DetectionType = "none" // DetectionTypeInjection is a general injection detection type DetectionTypeInjection DetectionType = "injection" // DetectionTypePromptInjection indicates a direct prompt injection attempt DetectionTypePromptInjection DetectionType = "prompt_injection" // DetectionTypeIndirectPromptInjection indicates an indirect prompt injection attempt DetectionTypeIndirectPromptInjection DetectionType = "indirect_prompt_injection" // DetectionTypeJailbreak indicates a jailbreak attempt DetectionTypeJailbreak DetectionType = "jailbreak" // DetectionTypeRoleChange indicates a role change attempt DetectionTypeRoleChange DetectionType = "role_change" // DetectionTypeSystemPrompt indicates a system prompt injection attempt DetectionTypeSystemPrompt DetectionType = "system_prompt" // DetectionTypeBoundaryViolation indicates a context boundary violation DetectionTypeBoundaryViolation DetectionType = "boundary_violation" // DetectionTypeDelimiterMisuse indicates misuse of delimiters DetectionTypeDelimiterMisuse DetectionType = "delimiter_misuse" // DetectionTypeUnusualPattern indicates an unusual pattern DetectionTypeUnusualPattern DetectionType = "unusual_pattern" // DetectionTypeProhibitedContent indicates prohibited content DetectionTypeProhibitedContent DetectionType = "prohibited_content" // DetectionTypeApprovalDenied indicates approval was denied DetectionTypeApprovalDenied DetectionType = "approval_denied" // DetectionTypeSensitiveInfo indicates sensitive information was detected DetectionTypeSensitiveInfo DetectionType = "sensitive_info" // DetectionTypeSystemInfo indicates system information was detected DetectionTypeSystemInfo DetectionType = "system_info" )
type EmergingPattern ¶
type EmergingPattern struct {
Pattern string `json:"pattern"`
Description string `json:"description"`
Source string `json:"source"`
DiscoveryTime time.Time `json:"discovery_time"`
LastSeen time.Time `json:"last_seen"`
Confidence float64 `json:"confidence"`
Examples []string `json:"examples"`
Validated bool `json:"validated"`
}
EmergingPattern represents a newly discovered pattern that hasn't been fully validated
type EnhancedApprovalConfig ¶
type EnhancedApprovalConfig struct {
EnableAutoApproval bool `json:"enable_auto_approval"`
EnableApprovalHistory bool `json:"enable_approval_history"`
EnableApprovalExpiration bool `json:"enable_approval_expiration"`
ApprovalThresholds map[string]float64 `json:"approval_thresholds"`
AutoApprovalRules map[string]AutoApprovalRule `json:"auto_approval_rules"`
ApprovalLevels map[string]ApprovalLevel `json:"approval_levels"`
DefaultApprovalLevel string `json:"default_approval_level"`
ApprovalTimeout time.Duration `json:"approval_timeout"`
}
EnhancedApprovalConfig defines the configuration for enhanced approval workflow
type EnhancedApprovalRequest ¶
type EnhancedApprovalRequest struct {
*ApprovalRequest
Status ApprovalStatus `json:"status"`
ApprovalLevel string `json:"approval_level"`
ApproverID string `json:"approver_id,omitempty"`
ApprovalTime time.Time `json:"approval_time,omitempty"`
ExpirationTime time.Time `json:"expiration_time"`
ApprovalHistory []*ApprovalAction `json:"approval_history,omitempty"`
AutoApprovalEligible bool `json:"auto_approval_eligible"`
AutoApprovalReason string `json:"auto_approval_reason,omitempty"`
}
EnhancedApprovalRequest extends the ApprovalRequest with more information
type EnhancedApprovalWorkflow ¶
type EnhancedApprovalWorkflow struct {
*ApprovalWorkflow
// contains filtered or unexported fields
}
EnhancedApprovalWorkflow extends the ApprovalWorkflow with more sophisticated approval capabilities
func NewEnhancedApprovalWorkflow ¶
func NewEnhancedApprovalWorkflow(config *ProtectionConfig, dataDir string) (*EnhancedApprovalWorkflow, error)
NewEnhancedApprovalWorkflow creates a new enhanced approval workflow
func (*EnhancedApprovalWorkflow) AddApprovalLevel ¶
func (w *EnhancedApprovalWorkflow) AddApprovalLevel(name string, level ApprovalLevel)
AddApprovalLevel adds an approval level
func (*EnhancedApprovalWorkflow) AddAutoApprovalRule ¶
func (w *EnhancedApprovalWorkflow) AddAutoApprovalRule(rule AutoApprovalRule)
AddAutoApprovalRule adds an auto-approval rule
func (*EnhancedApprovalWorkflow) ApproveRequest ¶
func (w *EnhancedApprovalWorkflow) ApproveRequest(requestID string, approverID string, reason string) error
ApproveRequest approves an approval request
func (*EnhancedApprovalWorkflow) EnableAutoApproval ¶
func (w *EnhancedApprovalWorkflow) EnableAutoApproval(enabled bool)
EnableAutoApproval enables or disables auto-approval
func (*EnhancedApprovalWorkflow) GetApprovalHistory ¶
func (w *EnhancedApprovalWorkflow) GetApprovalHistory() []*EnhancedApprovalRequest
GetApprovalHistory gets the approval history
func (*EnhancedApprovalWorkflow) GetApprovalRequest ¶
func (w *EnhancedApprovalWorkflow) GetApprovalRequest(requestID string) (*EnhancedApprovalRequest, error)
GetApprovalRequest gets an approval request by ID
func (*EnhancedApprovalWorkflow) GetPendingApprovals ¶
func (w *EnhancedApprovalWorkflow) GetPendingApprovals() []*EnhancedApprovalRequest
GetPendingApprovals gets all pending approval requests
func (*EnhancedApprovalWorkflow) RegisterApprovalHandler ¶
func (w *EnhancedApprovalWorkflow) RegisterApprovalHandler(name string, handler ApprovalHandlerFunc)
RegisterApprovalHandler registers a handler for approval requests
func (*EnhancedApprovalWorkflow) RejectRequest ¶
func (w *EnhancedApprovalWorkflow) RejectRequest(requestID string, approverID string, reason string) error
RejectRequest rejects an approval request
func (*EnhancedApprovalWorkflow) RequestApprovalEnhanced ¶
func (w *EnhancedApprovalWorkflow) RequestApprovalEnhanced(ctx context.Context, result *ProtectionResult) (bool, *ProtectionResult, error)
RequestApprovalEnhanced requests approval with enhanced capabilities
func (*EnhancedApprovalWorkflow) SetApprovalThreshold ¶
func (w *EnhancedApprovalWorkflow) SetApprovalThreshold(level string, threshold float64)
SetApprovalThreshold sets the threshold for requiring approval
func (*EnhancedApprovalWorkflow) SetDefaultApprovalLevel ¶
func (w *EnhancedApprovalWorkflow) SetDefaultApprovalLevel(level string) error
SetDefaultApprovalLevel sets the default approval level
type EnhancedContentFilter ¶
type EnhancedContentFilter struct {
// contains filtered or unexported fields
}
EnhancedContentFilter represents an enhanced content filtering system
func NewEnhancedContentFilter ¶
func NewEnhancedContentFilter(config FilterConfig) *EnhancedContentFilter
NewEnhancedContentFilter creates a new enhanced content filter
func (*EnhancedContentFilter) Disable ¶ added in v0.8.0
func (cf *EnhancedContentFilter) Disable()
Disable disables the content filter
func (*EnhancedContentFilter) Enable ¶ added in v0.8.0
func (cf *EnhancedContentFilter) Enable()
Enable enables the content filter
func (*EnhancedContentFilter) FilterContent ¶ added in v0.8.0
func (cf *EnhancedContentFilter) FilterContent(ctx context.Context, content string) (*FilterResult, error)
FilterContent filters the given content and returns the result
func (*EnhancedContentFilter) GetConfig ¶ added in v0.8.0
func (cf *EnhancedContentFilter) GetConfig() FilterConfig
GetConfig returns a copy of the current configuration
func (*EnhancedContentFilter) IsEnabled ¶ added in v0.8.0
func (cf *EnhancedContentFilter) IsEnabled() bool
IsEnabled returns whether the filter is enabled
func (*EnhancedContentFilter) UpdatePatterns ¶ added in v0.8.0
func (cf *EnhancedContentFilter) UpdatePatterns(allowedPatterns, blockedPatterns []string) error
UpdatePatterns updates the filtering patterns
type EnhancedContextBoundaryEnforcer ¶
type EnhancedContextBoundaryEnforcer struct {
*ContextBoundaryEnforcer
// contains filtered or unexported fields
}
EnhancedContextBoundaryEnforcer extends the ContextBoundaryEnforcer with more sophisticated boundary enforcement
func NewEnhancedContextBoundaryEnforcer ¶
func NewEnhancedContextBoundaryEnforcer(config *ProtectionConfig) *EnhancedContextBoundaryEnforcer
NewEnhancedContextBoundaryEnforcer creates a new enhanced context boundary enforcer
func (*EnhancedContextBoundaryEnforcer) EnableStrictMode ¶
func (e *EnhancedContextBoundaryEnforcer) EnableStrictMode(enabled bool)
EnableStrictMode enables or disables strict mode
func (*EnhancedContextBoundaryEnforcer) EnforceBoundariesEnhanced ¶
func (e *EnhancedContextBoundaryEnforcer) EnforceBoundariesEnhanced(ctx context.Context, prompt string) (string, *ProtectionResult, error)
EnforceBoundariesEnhanced enforces context boundaries with enhanced protection
func (*EnhancedContextBoundaryEnforcer) GetBoundaryViolations ¶
func (e *EnhancedContextBoundaryEnforcer) GetBoundaryViolations() map[string]int
GetBoundaryViolations returns the boundary violations
func (*EnhancedContextBoundaryEnforcer) GetContextHistory ¶
func (e *EnhancedContextBoundaryEnforcer) GetContextHistory() []*ContextHistoryEntry
GetContextHistory returns the context history
type EnhancedInjectionPatternLibrary ¶
type EnhancedInjectionPatternLibrary struct {
*InjectionPatternLibrary
// contains filtered or unexported fields
}
EnhancedInjectionPatternLibrary extends the InjectionPatternLibrary with more sophisticated pattern management
func NewEnhancedInjectionPatternLibrary ¶
func NewEnhancedInjectionPatternLibrary(dataDir string) (*EnhancedInjectionPatternLibrary, error)
NewEnhancedInjectionPatternLibrary creates a new enhanced injection pattern library
func (*EnhancedInjectionPatternLibrary) AddCustomPattern ¶
func (l *EnhancedInjectionPatternLibrary) AddCustomPattern(pattern string, description string, creator string, categories []string) error
AddCustomPattern adds a new custom pattern
func (*EnhancedInjectionPatternLibrary) AddEmergingPattern ¶
func (l *EnhancedInjectionPatternLibrary) AddEmergingPattern(pattern string, description string, source string, examples []string, confidence float64) error
AddEmergingPattern adds a new emerging pattern
func (*EnhancedInjectionPatternLibrary) DetectPatternsEnhanced ¶
func (l *EnhancedInjectionPatternLibrary) DetectPatternsEnhanced(prompt string, result *ProtectionResult)
DetectPatternsEnhanced detects patterns in a prompt with enhanced detection
func (*EnhancedInjectionPatternLibrary) EnableCustomPattern ¶
func (l *EnhancedInjectionPatternLibrary) EnableCustomPattern(pattern string, enabled bool) error
EnableCustomPattern enables or disables a custom pattern
func (*EnhancedInjectionPatternLibrary) GetCustomPatterns ¶
func (l *EnhancedInjectionPatternLibrary) GetCustomPatterns() []*CustomPattern
GetCustomPatterns gets all custom patterns
func (*EnhancedInjectionPatternLibrary) GetEmergingPatterns ¶
func (l *EnhancedInjectionPatternLibrary) GetEmergingPatterns() []*EmergingPattern
GetEmergingPatterns gets all emerging patterns
func (*EnhancedInjectionPatternLibrary) GetPatternStats ¶
func (l *EnhancedInjectionPatternLibrary) GetPatternStats(pattern string) (*PatternStats, error)
GetPatternStats gets statistics for a pattern
func (*EnhancedInjectionPatternLibrary) GetPatternsByCategory ¶
func (l *EnhancedInjectionPatternLibrary) GetPatternsByCategory(category string) ([]*InjectionPattern, error)
GetPatternsByCategory gets patterns by category
func (*EnhancedInjectionPatternLibrary) ValidateEmergingPattern ¶
func (l *EnhancedInjectionPatternLibrary) ValidateEmergingPattern(pattern string, validated bool) error
ValidateEmergingPattern validates an emerging pattern
type EnhancedInjectionReport ¶
type EnhancedInjectionReport struct {
*InjectionReport
Status ReportStatus `json:"status"`
Category string `json:"category"`
AnalysisResults map[string]interface{} `json:"analysis_results,omitempty"`
RelatedReports []string `json:"related_reports,omitempty"`
PatternMatches int `json:"pattern_matches"`
FalsePositiveRate float64 `json:"false_positive_rate"`
EffectivenessScore float64 `json:"effectiveness_score"`
CreatedBy string `json:"created_by"`
LastUpdated time.Time `json:"last_updated"`
}
EnhancedInjectionReport extends the InjectionReport with more information
type EnhancedProtectionConfig ¶
type EnhancedProtectionConfig struct {
Level ProtectionLevel `json:"level"`
EnableAdvancedDetection bool `json:"enable_advanced_detection"`
EnableEnhancedPatterns bool `json:"enable_enhanced_patterns"`
EnableEnhancedBoundaries bool `json:"enable_enhanced_boundaries"`
EnableEnhancedFiltering bool `json:"enable_enhanced_filtering"`
EnableEnhancedApproval bool `json:"enable_enhanced_approval"`
EnableEnhancedReporting bool `json:"enable_enhanced_reporting"`
EnableAdvancedMonitoring bool `json:"enable_advanced_monitoring"`
DataDirectory string `json:"data_directory"`
LogDirectory string `json:"log_directory"`
LogLevel string `json:"log_level"`
AnalysisInterval time.Duration `json:"analysis_interval"`
}
EnhancedProtectionConfig defines the configuration for enhanced protection
type EnhancedProtectionManager ¶
type EnhancedProtectionManager struct {
*ProtectionManager
// contains filtered or unexported fields
}
EnhancedProtectionManager extends the ProtectionManager with more sophisticated protection capabilities
func NewEnhancedProtectionManager ¶
func NewEnhancedProtectionManager(config *ProtectionConfig) (*EnhancedProtectionManager, error)
NewEnhancedProtectionManager creates a new enhanced protection manager
func (*EnhancedProtectionManager) AnalyzeReports ¶
func (pm *EnhancedProtectionManager) AnalyzeReports(ctx context.Context) error
AnalyzeReports analyzes all reports
func (*EnhancedProtectionManager) Close ¶
func (pm *EnhancedProtectionManager) Close() error
Close closes the protection manager and releases resources
func (*EnhancedProtectionManager) EnableComponent ¶
func (pm *EnhancedProtectionManager) EnableComponent(component string, enabled bool)
EnableComponent enables or disables a component
func (*EnhancedProtectionManager) GetApprovalWorkflow ¶
func (pm *EnhancedProtectionManager) GetApprovalWorkflow() *EnhancedApprovalWorkflow
GetApprovalWorkflow gets the enhanced approval workflow
func (*EnhancedProtectionManager) GetPatternLibrary ¶
func (pm *EnhancedProtectionManager) GetPatternLibrary() *EnhancedInjectionPatternLibrary
GetPatternLibrary gets the enhanced pattern library
func (*EnhancedProtectionManager) GetReportingSystem ¶
func (pm *EnhancedProtectionManager) GetReportingSystem() *EnhancedReportingSystem
GetReportingSystem gets the enhanced reporting system
func (*EnhancedProtectionManager) GetTemplateMonitor ¶
func (pm *EnhancedProtectionManager) GetTemplateMonitor() *AdvancedTemplateMonitor
GetTemplateMonitor gets the advanced template monitor
func (*EnhancedProtectionManager) ProtectPromptEnhanced ¶
func (pm *EnhancedProtectionManager) ProtectPromptEnhanced(ctx context.Context, prompt string, userID string, sessionID string, templateID string) (string, *ProtectionResult, error)
ProtectPromptEnhanced protects against prompt injection with enhanced protection
func (*EnhancedProtectionManager) ProtectResponseEnhanced ¶
func (pm *EnhancedProtectionManager) ProtectResponseEnhanced(ctx context.Context, response string, originalPrompt string, userID string, sessionID string, templateID string) (string, *ProtectionResult, error)
ProtectResponseEnhanced protects against prompt injection in responses with enhanced protection
func (*EnhancedProtectionManager) SetProtectionLevel ¶
func (pm *EnhancedProtectionManager) SetProtectionLevel(level ProtectionLevel)
SetProtectionLevel sets the protection level
func (*EnhancedProtectionManager) StartMonitoring ¶
func (pm *EnhancedProtectionManager) StartMonitoring(ctx context.Context) error
StartMonitoring starts the template monitoring
func (*EnhancedProtectionManager) StopMonitoring ¶
func (pm *EnhancedProtectionManager) StopMonitoring()
StopMonitoring stops the template monitoring
type EnhancedReportingConfig ¶
type EnhancedReportingConfig struct {
EnableAutomaticReporting bool `json:"enable_automatic_reporting"`
EnableReportSharing bool `json:"enable_report_sharing"`
EnableReportAnalysis bool `json:"enable_report_analysis"`
ReportingThreshold float64 `json:"reporting_threshold"`
ReportCategories []string `json:"report_categories"`
ReportingEndpoints map[string]string `json:"reporting_endpoints"`
AnalysisInterval time.Duration `json:"analysis_interval"`
}
EnhancedReportingConfig defines the configuration for enhanced reporting
type EnhancedReportingSystem ¶
type EnhancedReportingSystem struct {
*ReportingSystem
// contains filtered or unexported fields
}
EnhancedReportingSystem extends the ReportingSystem with more sophisticated reporting capabilities
func NewEnhancedReportingSystem ¶
func NewEnhancedReportingSystem(config *ProtectionConfig, patternLibrary *EnhancedInjectionPatternLibrary, dataDir string) (*EnhancedReportingSystem, error)
NewEnhancedReportingSystem creates a new enhanced reporting system
func (*EnhancedReportingSystem) AddReportingEndpoint ¶
func (r *EnhancedReportingSystem) AddReportingEndpoint(name string, endpoint string)
AddReportingEndpoint adds a reporting endpoint
func (*EnhancedReportingSystem) AnalyzeReports ¶
func (r *EnhancedReportingSystem) AnalyzeReports(ctx context.Context) error
AnalyzeReports analyzes all reports
func (*EnhancedReportingSystem) CreateCustomReport ¶
func (r *EnhancedReportingSystem) CreateCustomReport(ctx context.Context, detectionType DetectionType, pattern string, example string, description string, createdBy string) (*EnhancedInjectionReport, error)
CreateCustomReport creates a custom report
func (*EnhancedReportingSystem) EnableAutomaticReporting ¶
func (r *EnhancedReportingSystem) EnableAutomaticReporting(enabled bool)
EnableAutomaticReporting enables or disables automatic reporting
func (*EnhancedReportingSystem) GetReport ¶
func (r *EnhancedReportingSystem) GetReport(reportID string) (*EnhancedInjectionReport, error)
GetReport gets a report by ID
func (*EnhancedReportingSystem) GetReports ¶
func (r *EnhancedReportingSystem) GetReports() []*EnhancedInjectionReport
GetReports gets all reports
func (*EnhancedReportingSystem) GetReportsByCategory ¶
func (r *EnhancedReportingSystem) GetReportsByCategory(category string) []*EnhancedInjectionReport
GetReportsByCategory gets reports by category
func (*EnhancedReportingSystem) GetReportsByStatus ¶
func (r *EnhancedReportingSystem) GetReportsByStatus(status ReportStatus) []*EnhancedInjectionReport
GetReportsByStatus gets reports by status
func (*EnhancedReportingSystem) RegisterReportHandler ¶
func (r *EnhancedReportingSystem) RegisterReportHandler(name string, handler ReportHandlerFunc)
RegisterReportHandler registers a handler for reports
func (*EnhancedReportingSystem) ReportInjectionEnhanced ¶
func (r *EnhancedReportingSystem) ReportInjectionEnhanced(ctx context.Context, detections []*Detection, prompt string, response string) error
ReportInjectionEnhanced reports an injection technique with enhanced capabilities
func (*EnhancedReportingSystem) SetReportingThreshold ¶
func (r *EnhancedReportingSystem) SetReportingThreshold(threshold float64)
SetReportingThreshold sets the threshold for reporting
func (*EnhancedReportingSystem) ShareReport ¶
func (r *EnhancedReportingSystem) ShareReport(ctx context.Context, reportID string, destination string) error
ShareReport shares a report
func (*EnhancedReportingSystem) VerifyReport ¶
func (r *EnhancedReportingSystem) VerifyReport(ctx context.Context, reportID string, verified bool, reason string) error
VerifyReport verifies a report
type FilterConfig ¶ added in v0.8.0
type FilterConfig struct {
MaxContentLength int
Timeout time.Duration
StrictMode bool
AllowedPatterns []string
BlockedPatterns []string
}
FilterConfig holds configuration for content filtering
type FilterResult ¶ added in v0.8.0
type FilterResult struct {
Allowed bool
Reason string
Score float64
Violations []string
Detections []*Detection
RiskScore float64
ActionTaken ActionType
ProcessTime time.Duration
}
FilterResult represents the result of content filtering
type InjectionPattern ¶
type InjectionPattern struct {
// ID is a unique identifier for the pattern
ID string `json:"id"`
// Name is a human-readable name for the pattern
Name string `json:"name"`
// Description is a description of the pattern
Description string `json:"description"`
// Category is the category of the pattern
Category PatternCategory `json:"category"`
// Pattern is the regular expression pattern
Pattern string `json:"pattern"`
// Confidence is the confidence level for the pattern (0.0-1.0)
Confidence float64 `json:"confidence"`
// Severity is the severity level for the pattern (0.0-1.0)
Severity float64 `json:"severity"`
// Examples are examples of the pattern
Examples []string `json:"examples,omitempty"`
// Tags are tags for the pattern
Tags []string `json:"tags,omitempty"`
// CreatedAt is the time the pattern was created
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is the time the pattern was last updated
UpdatedAt time.Time `json:"updated_at"`
// Enabled indicates if the pattern is enabled
Enabled bool `json:"enabled"`
// CompiledPattern is the compiled regular expression
CompiledPattern *regexp.Regexp `json:"-"`
}
InjectionPattern defines a pattern for detecting prompt injection
type InjectionPatternLibrary ¶
type InjectionPatternLibrary struct {
// contains filtered or unexported fields
}
InjectionPatternLibrary manages a library of prompt injection patterns
func NewInjectionPatternLibrary ¶
func NewInjectionPatternLibrary() *InjectionPatternLibrary
NewInjectionPatternLibrary creates a new injection pattern library
func (*InjectionPatternLibrary) AddPattern ¶
func (l *InjectionPatternLibrary) AddPattern(pattern *InjectionPattern) error
AddPattern adds a pattern to the library
func (*InjectionPatternLibrary) DetectPatterns ¶
func (l *InjectionPatternLibrary) DetectPatterns(prompt string, result *ProtectionResult)
DetectPatterns detects patterns in a prompt
func (*InjectionPatternLibrary) DisablePattern ¶
func (l *InjectionPatternLibrary) DisablePattern(id string)
DisablePattern disables a pattern
func (*InjectionPatternLibrary) EnablePattern ¶
func (l *InjectionPatternLibrary) EnablePattern(id string)
EnablePattern enables a pattern
func (*InjectionPatternLibrary) GetAllPatterns ¶
func (l *InjectionPatternLibrary) GetAllPatterns() []*InjectionPattern
GetAllPatterns gets all patterns
func (*InjectionPatternLibrary) GetPattern ¶
func (l *InjectionPatternLibrary) GetPattern(id string) *InjectionPattern
GetPattern gets a pattern by ID
func (*InjectionPatternLibrary) GetPatternsByCategory ¶
func (l *InjectionPatternLibrary) GetPatternsByCategory(category PatternCategory) []*InjectionPattern
GetPatternsByCategory gets patterns by category
func (*InjectionPatternLibrary) LoadPatternsFromFile ¶
func (l *InjectionPatternLibrary) LoadPatternsFromFile(filePath string) error
LoadPatternsFromFile loads patterns from a JSON file
func (*InjectionPatternLibrary) RemovePattern ¶
func (l *InjectionPatternLibrary) RemovePattern(id string)
RemovePattern removes a pattern from the library
func (*InjectionPatternLibrary) SavePatternsToFile ¶
func (l *InjectionPatternLibrary) SavePatternsToFile(filePath string) error
SavePatternsToFile saves patterns to a JSON file
type InjectionReport ¶
type InjectionReport struct {
// ReportID is a unique identifier for the report
ReportID string `json:"report_id"`
// DetectionType is the type of detection
DetectionType DetectionType `json:"detection_type"`
// Pattern is the pattern that triggered the detection
Pattern string `json:"pattern,omitempty"`
// Example is an example of the injection technique
Example string `json:"example"`
// Confidence is the confidence level of the detection (0.0-1.0)
Confidence float64 `json:"confidence"`
// Severity is the severity level of the injection technique (0.0-1.0)
Severity float64 `json:"severity"`
// Description is a human-readable description of the injection technique
Description string `json:"description"`
// Timestamp is the time of the report
Timestamp time.Time `json:"timestamp"`
// Source is the source of the report
Source string `json:"source,omitempty"`
// Metadata contains additional metadata about the report
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
InjectionReport defines a report of a new injection technique
type JailbreakDetectionConfig ¶
type JailbreakDetectionConfig struct {
// EnableRoleChangeDetection enables detection of role changes
EnableRoleChangeDetection bool `json:"enable_role_change_detection"`
// EnableSystemPromptDetection enables detection of system prompt injections
EnableSystemPromptDetection bool `json:"enable_system_prompt_detection"`
// EnableDelimiterMisuseDetection enables detection of delimiter misuse
EnableDelimiterMisuseDetection bool `json:"enable_delimiter_misuse_detection"`
// EnableInstructionOverrideDetection enables detection of instruction overrides
EnableInstructionOverrideDetection bool `json:"enable_instruction_override_detection"`
// DetectionThreshold is the threshold for detection (0.0-1.0)
DetectionThreshold float64 `json:"detection_threshold"`
}
JailbreakDetectionConfig defines the configuration for jailbreak detection
type JailbreakDetector ¶
type JailbreakDetector struct {
// contains filtered or unexported fields
}
JailbreakDetector detects jailbreaking attempts in prompts
func NewJailbreakDetector ¶
func NewJailbreakDetector(config *ProtectionConfig, patternLibrary *InjectionPatternLibrary) *JailbreakDetector
NewJailbreakDetector creates a new jailbreak detector
func (*JailbreakDetector) DetectJailbreak ¶
func (d *JailbreakDetector) DetectJailbreak(ctx context.Context, prompt string) (*ProtectionResult, error)
DetectJailbreak detects jailbreaking attempts in a prompt
type MonitoringConfig ¶
type MonitoringConfig struct {
// MonitoringInterval is the interval for real-time monitoring checks
MonitoringInterval time.Duration `json:"monitoring_interval"`
// MaxPatternHistory is the maximum number of patterns to keep in history
MaxPatternHistory int `json:"max_pattern_history"`
// AnomalyThreshold is the threshold for anomaly detection (0.0-1.0)
AnomalyThreshold float64 `json:"anomaly_threshold"`
// EnableAnomalyDetection enables anomaly detection
EnableAnomalyDetection bool `json:"enable_anomaly_detection"`
}
MonitoringConfig defines the configuration for real-time monitoring
type PatternCategory ¶
type PatternCategory string
PatternCategory defines the category of a pattern
const ( // CategoryPromptInjection is for direct prompt injection patterns CategoryPromptInjection PatternCategory = "prompt_injection" // CategoryIndirectPromptInjection is for indirect prompt injection patterns CategoryIndirectPromptInjection PatternCategory = "indirect_prompt_injection" // CategoryJailbreak is for jailbreak patterns CategoryJailbreak PatternCategory = "jailbreak" // CategoryRoleChange is for role change patterns CategoryRoleChange PatternCategory = "role_change" // CategorySystemPrompt is for system prompt patterns CategorySystemPrompt PatternCategory = "system_prompt" // CategoryDelimiter is for delimiter patterns CategoryDelimiter PatternCategory = "delimiter" // CategoryOverride is for instruction override patterns CategoryOverride PatternCategory = "override" // CategoryCustom is for custom patterns CategoryCustom PatternCategory = "custom" )
type PatternStats ¶
type PatternStats struct {
Pattern string `json:"pattern"`
MatchCount int `json:"match_count"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
EffectivenessScore float64 `json:"effectiveness_score"`
FalsePositiveRate float64 `json:"false_positive_rate"`
Categories []string `json:"categories"`
}
PatternStats tracks statistics for pattern matches
type PromptProtectionMiddleware ¶
type PromptProtectionMiddleware struct {
// contains filtered or unexported fields
}
PromptProtectionMiddleware is a middleware that provides protection against prompt injection
func NewPromptProtectionMiddleware ¶
func NewPromptProtectionMiddleware(config *ProtectionConfig) (*PromptProtectionMiddleware, error)
NewPromptProtectionMiddleware creates a new prompt protection middleware
func (*PromptProtectionMiddleware) Middleware ¶
func (m *PromptProtectionMiddleware) Middleware(next http.Handler) http.Handler
Middleware returns an HTTP middleware function
type ProtectionConfig ¶
type ProtectionConfig struct {
// Level is the protection level to apply
Level ProtectionLevel
// EnableContextBoundaries enables context boundary enforcement
EnableContextBoundaries bool
// EnableJailbreakDetection enables detection of jailbreaking attempts
EnableJailbreakDetection bool
// EnableRealTimeMonitoring enables real-time monitoring of template patterns
EnableRealTimeMonitoring bool
// EnableContentFiltering enables filtering of generated outputs
EnableContentFiltering bool
// EnableApprovalWorkflow enables approval workflow for high-risk operations
EnableApprovalWorkflow bool
// EnableReportingSystem enables reporting of new prompt injection techniques
EnableReportingSystem bool
// CustomPatterns allows for custom prompt injection patterns
CustomPatterns []string
// AllowedRoles defines the roles that the LLM is allowed to take
AllowedRoles []string
// ForbiddenRoles defines the roles that the LLM is not allowed to take
ForbiddenRoles []string
// MaxPromptLength is the maximum allowed length for prompts
MaxPromptLength int
// SanitizationLevel defines how aggressively to sanitize inputs
SanitizationLevel int
// ApprovalThreshold is the risk score threshold for requiring approval
ApprovalThreshold float64
// RiskThreshold is the risk score threshold for protective actions
RiskThreshold float64
// ApprovalCallback is called when approval is required
ApprovalCallback func(context.Context, *ApprovalRequest) (bool, error)
// ReportingCallback is called when a new injection technique is detected
ReportingCallback func(context.Context, *InjectionReport) error
// MonitoringInterval is the interval for real-time monitoring checks
MonitoringInterval time.Duration
}
ProtectionConfig defines the configuration for the prompt injection protection system
func DefaultProtectionConfig ¶
func DefaultProtectionConfig() *ProtectionConfig
DefaultProtectionConfig returns the default protection configuration
func HighSecurityProtectionConfig ¶
func HighSecurityProtectionConfig() *ProtectionConfig
HighSecurityProtectionConfig returns a high-security protection configuration
type ProtectionLevel ¶
type ProtectionLevel int
ProtectionLevel defines the level of protection to apply
const ( // LevelLow provides basic protection with minimal impact on performance LevelLow ProtectionLevel = iota // LevelMedium provides balanced protection and performance LevelMedium // LevelHigh provides maximum protection with potential performance impact LevelHigh // LevelCustom allows for custom configuration of protection mechanisms LevelCustom )
type ProtectionManager ¶
type ProtectionManager struct {
// contains filtered or unexported fields
}
ProtectionManager manages the prompt injection protection system
func NewProtectionManager ¶
func NewProtectionManager(config *ProtectionConfig) (*ProtectionManager, error)
NewProtectionManager creates a new protection manager
func (*ProtectionManager) Close ¶
func (pm *ProtectionManager) Close() error
Close closes the protection manager and releases resources
func (*ProtectionManager) ProtectPrompt ¶
func (pm *ProtectionManager) ProtectPrompt(ctx context.Context, prompt string) (string, *ProtectionResult, error)
ProtectPrompt protects against prompt injection in user inputs
func (*ProtectionManager) ProtectResponse ¶
func (pm *ProtectionManager) ProtectResponse(ctx context.Context, response string, originalPrompt string) (string, *ProtectionResult, error)
ProtectResponse protects against prompt injection in LLM responses
type ProtectionResult ¶
type ProtectionResult struct {
// OriginalPrompt is the original prompt
OriginalPrompt string `json:"original_prompt,omitempty"`
// ProtectedPrompt is the protected prompt
ProtectedPrompt string `json:"protected_prompt,omitempty"`
// OriginalResponse is the original response
OriginalResponse string `json:"original_response,omitempty"`
// ProtectedResponse is the protected response
ProtectedResponse string `json:"protected_response,omitempty"`
// Detections is a list of detections
Detections []*Detection `json:"detections,omitempty"`
// RiskScore is the overall risk score (0.0-1.0)
RiskScore float64 `json:"risk_score"`
// ActionTaken is the action taken by the protection system
ActionTaken ActionType `json:"action_taken"`
// Timestamp is the time of the protection operation
Timestamp time.Time `json:"timestamp"`
// ProcessingTime is the time taken to process the protection operation
ProcessingTime time.Duration `json:"processing_time,omitempty"`
}
ProtectionResult defines the result of a protection operation
type ReportHandlerFunc ¶
type ReportHandlerFunc func(context.Context, *EnhancedInjectionReport) error
ReportHandlerFunc defines a function that handles reports
type ReportStatus ¶
type ReportStatus string
ReportStatus defines the status of a report
const ( // ReportStatusNew indicates a new report ReportStatusNew ReportStatus = "new" // ReportStatusAnalyzed indicates an analyzed report ReportStatusAnalyzed ReportStatus = "analyzed" // ReportStatusVerified indicates a verified report ReportStatusVerified ReportStatus = "verified" // ReportStatusRejected indicates a rejected report ReportStatusRejected ReportStatus = "rejected" ReportStatusShared ReportStatus = "shared" )
type ReportingConfig ¶
type ReportingConfig struct {
// ReportingEndpoint is the endpoint for reporting
ReportingEndpoint string `json:"reporting_endpoint,omitempty"`
// ReportingInterval is the interval for reporting
ReportingInterval time.Duration `json:"reporting_interval"`
// MaxReportHistory is the maximum number of reports to keep in history
MaxReportHistory int `json:"max_report_history"`
// EnableLocalStorage enables local storage of reports
EnableLocalStorage bool `json:"enable_local_storage"`
// LocalStoragePath is the path for local storage
LocalStoragePath string `json:"local_storage_path,omitempty"`
}
ReportingConfig defines the configuration for the reporting system
type ReportingSystem ¶
type ReportingSystem struct {
// contains filtered or unexported fields
}
ReportingSystem manages reporting of new prompt injection techniques
func NewReportingSystem ¶
func NewReportingSystem(config *ProtectionConfig) *ReportingSystem
NewReportingSystem creates a new reporting system
func (*ReportingSystem) Close ¶
func (r *ReportingSystem) Close() error
Close closes the reporting system and releases resources
func (*ReportingSystem) GetReportByID ¶
func (r *ReportingSystem) GetReportByID(reportID string) *InjectionReport
GetReportByID gets a report by ID
func (*ReportingSystem) GetReports ¶
func (r *ReportingSystem) GetReports() []*InjectionReport
GetReports gets all reports
func (*ReportingSystem) GetReportsByType ¶
func (r *ReportingSystem) GetReportsByType(detectionType DetectionType) []*InjectionReport
GetReportsByType gets reports by detection type
func (*ReportingSystem) ReportDetections ¶
func (r *ReportingSystem) ReportDetections(ctx context.Context, result *ProtectionResult)
ReportDetections reports detections from a protection result
type RoleDefinition ¶
type RoleDefinition struct {
Name string `json:"name"`
AllowedActions []string `json:"allowed_actions"`
ForbiddenActions []string `json:"forbidden_actions"`
Capabilities []string `json:"capabilities"`
Limitations []string `json:"limitations"`
SecurityLevel int `json:"security_level"`
}
RoleDefinition defines a role boundary
type SessionStats ¶
type SessionStats struct {
SessionID string `json:"session_id"`
UserID string `json:"user_id"`
StartTime time.Time `json:"start_time"`
LastActivityTime time.Time `json:"last_activity_time"`
ExecutionCount int `json:"execution_count"`
AverageRiskScore float64 `json:"average_risk_score"`
DetectionCount int `json:"detection_count"`
DetectionTypes map[DetectionType]int `json:"detection_types"`
TemplateUsage map[string]int `json:"template_usage"`
AnomalyScore float64 `json:"anomaly_score"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
SessionStats tracks statistics for a session
type TemplateMonitor ¶
type TemplateMonitor struct {
// contains filtered or unexported fields
}
TemplateMonitor monitors templates for unusual patterns
func NewTemplateMonitor ¶
func NewTemplateMonitor(config *ProtectionConfig, patternLibrary *InjectionPatternLibrary) *TemplateMonitor
NewTemplateMonitor creates a new template monitor
func (*TemplateMonitor) GetAllPatternStats ¶
func (m *TemplateMonitor) GetAllPatternStats() []*TemplatePatternStats
GetAllPatternStats gets all pattern statistics
func (*TemplateMonitor) GetPatternStats ¶
func (m *TemplateMonitor) GetPatternStats(pattern string) *TemplatePatternStats
GetPatternStats gets the statistics for a pattern
func (*TemplateMonitor) MonitorPrompt ¶
func (m *TemplateMonitor) MonitorPrompt(ctx context.Context, result *ProtectionResult)
MonitorPrompt monitors a prompt for unusual patterns
func (*TemplateMonitor) Start ¶
func (m *TemplateMonitor) Start(ctx context.Context)
Start starts the template monitor
type TemplatePatternStats ¶
type TemplatePatternStats struct {
// Pattern is the template pattern
Pattern string `json:"pattern"`
// Count is the number of times the pattern has been seen
Count int `json:"count"`
// FirstSeen is the time the pattern was first seen
FirstSeen time.Time `json:"first_seen"`
// LastSeen is the time the pattern was last seen
LastSeen time.Time `json:"last_seen"`
// AverageRiskScore is the average risk score for the pattern
AverageRiskScore float64 `json:"average_risk_score"`
// DetectionTypes is a map of detection types to counts
DetectionTypes map[DetectionType]int `json:"detection_types,omitempty"`
// Examples contains examples of the pattern
Examples []string `json:"examples,omitempty"`
// Metadata contains additional metadata about the pattern
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
TemplatePatternStats defines statistics for a template pattern
type TemplateStats ¶
type TemplateStats struct {
TemplateID string `json:"template_id"`
TemplateName string `json:"template_name"`
ExecutionCount int `json:"execution_count"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
AverageRiskScore float64 `json:"average_risk_score"`
DetectionCount int `json:"detection_count"`
DetectionTypes map[DetectionType]int `json:"detection_types"`
SuccessRate float64 `json:"success_rate"`
AverageResponseTime time.Duration `json:"average_response_time"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
TemplateStats tracks statistics for a template
type UserStats ¶
type UserStats struct {
UserID string `json:"user_id"`
TemplateUsage map[string]int `json:"template_usage"`
TotalExecutions int `json:"total_executions"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
AverageRiskScore float64 `json:"average_risk_score"`
DetectionCount int `json:"detection_count"`
DetectionTypes map[DetectionType]int `json:"detection_types"`
SuccessRate float64 `json:"success_rate"`
AnomalyScore float64 `json:"anomaly_score"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
UserStats tracks statistics for a user
Source Files
¶
- advanced_jailbreak_detector.go
- advanced_template_monitor.go
- approval_workflow.go
- content_filter.go
- context_boundary.go
- enhanced_approval_workflow.go
- enhanced_content_filter.go
- enhanced_context_boundary.go
- enhanced_pattern_library.go
- enhanced_protection_manager.go
- enhanced_reporting_system.go
- jailbreak_detector.go
- middleware.go
- pattern_age.go
- pattern_library.go
- protection.go
- reporting_system.go
- template_monitor.go
- types.go
- utils.go