Documentation
¶
Overview ¶
Package extension provides core functionality for the extension system: error handling, validation, defense, and logging
Error Handling ¶
Uses the Error struct and ErrorCode enum for unified error handling:
err := extension.NewError(extension.ErrCodeInvalidInput, "invalid input")
err = err.WithContext("user_id", 123).WithContext("field", "email")
if err.IsRecoverable() {
// can retry
return retryOperation()
}
if err.IsFatal() {
return err
}
Error Code System ¶
46 error codes divided into 8 categories (1000-8999):
Registry errors (1000-1999): NotFound, AlreadyRegistered, InvalidMetadata Validation errors (2000-2999): InvalidInput, FieldSizeMismatch, EncodingError Parsing errors (3000-3999): ParseFailed, InvalidFormat, MalformedData Analysis errors (4000-4999): AnalysisFailed, ResourceExhausted Configuration errors (5000-5999): InvalidConfig, MissingConfig Plugin errors (6000-6999): PluginNotFound, PluginLoadFailed System errors (7000-7999): SystemError, MemoryExhausted, Timeout Security errors (8000-8999): SecurityViolation, Unauthorized
Severity Levels ¶
5 error severity levels:
SeverityInfo (0) - Info, recoverable SeverityWarning (1) - Warning, recoverable SeverityError (2) - Error, recoverable SeverityCritical (3) - Critical, non-recoverable SeverityFatal (4) - Fatal, non-recoverable
Input Validation ¶
Using DefaultValidator for data validation:
validator := extension.NewDefaultValidator()
if err := validator.ValidateData(data); err != nil {
return err
}
Defense System ¶
Using RequestGuard to protect API endpoints:
policy := extension.DefaultDefensePolicy()
guard := extension.NewRequestGuard(policy)
if err := guard.ValidateRequest(request); err != nil {
return err
}
Safe Execution ¶
Catches panics and recovers:
extension.SafeExecuteWithRecovery(
func() error { return unsafeOp() },
func(r interface{}) { log.Printf("panic: %v", r) },
)
Index ¶
- Constants
- Variables
- func ComparePerformance(oldDuration, newDuration time.Duration)
- func Example1_BasicUsage()
- func Example2_LoggingMiddleware()
- func Example3_CachingMiddleware()
- func Example4_ABTest()
- func Example5_SelectiveStrategy()
- func GetRegistryStats() map[string]interface{}
- func InitializeECHExtension() error
- func LoadPlugins(configPath string) error
- func RegisterAnalyzer(extType ExtensionType, analyzer Analyzer) error
- func RegisterAnalyzerBuilder(extType ExtensionType, builder func() (Analyzer, error)) error
- func RegisterComparerBuilder(name string, builder func() (Comparer, error)) error
- func RegisterExtension(metadata *ExtensionMetadata) error
- func RegisterHandler(extType ExtensionType, handler Handler) error
- func RegisterHandlerBuilder(name string, builder func() (Handler, error)) error
- func RegisterParser(extType ExtensionType, parser Parser) error
- func RegisterParserBuilder(extType ExtensionType, builder func() (Parser, error)) error
- func RegisterPlugin(name string, plugin Plugin) error
- func RegisterPluginBuilder(name string, builder func() (Plugin, error)) error
- func RegisterTransformBuilder(name string, builder func() (Transform, error)) error
- func RegisterValidatorBuilder(name string, builder func() (Validator, error)) error
- func SafeExecute(fn func() error) (err error)
- func SafeExecuteWithRecovery(fn func() error, handler func(interface{})) error
- func SafeParseInt(s string, base, bitSize int) (int64, error)
- func ShouldUseProcessWithPipeline(scenario *ProcessingScenario) bool
- func ShowBestPractices()
- func ShowMigrationTimeline()
- func WaitForCanaryCompletion(ctx context.Context, collector *CanaryMetricsCollector, duration time.Duration)
- type AnalysisResult
- type AnalyzeStage
- type Analyzer
- type AnalyzerFactory
- type AuditConfig
- type AuditEvent
- type Auditable
- type CanaryConfig
- type CanaryHealthCheck
- type CanaryLifecycle
- type CanaryMetrics
- type CanaryMetricsCollector
- func (c *CanaryMetricsCollector) DisableCanary()
- func (c *CanaryMetricsCollector) EnableCanary(stage CanaryStage, percentage float64, duration time.Duration)
- func (c *CanaryMetricsCollector) GenerateCanaryReport(startTime time.Time) *CanaryReport
- func (c *CanaryMetricsCollector) GetCurrentMetrics() *CanaryMetrics
- func (c *CanaryMetricsCollector) GetMetricsHistory(hours int) []*CanaryMetrics
- func (c *CanaryMetricsCollector) RecordCacheHit(hit bool)
- func (c *CanaryMetricsCollector) RecordRequest(requestID string, useNewMethod bool, duration time.Duration, success bool)
- func (c *CanaryMetricsCollector) SnapshotMetrics()
- type CanaryReport
- type CanaryRouter
- type CanaryStage
- type CanaryThresholds
- type Closeable
- type Comparer
- type ComparerFactory
- type Component
- type ComponentInfo
- type Config
- type ConfigProvider
- type Container
- func (c *Container) Get(name string) (interface{}, error)
- func (c *Container) GetConfig() *Config
- func (c *Container) GetLogger(name string) (*SimpleLogger, error)
- func (c *Container) GetRateLimiter() (*RateLimiter, error)
- func (c *Container) GetRequestGuard() (*RequestGuard, error)
- func (c *Container) GetSecurityAuditor() (*SecurityAuditor, error)
- func (c *Container) GetValidator() (*DefaultValidator, error)
- func (c *Container) Initialize() error
- func (c *Container) Register(name string, factory func() (interface{}, error)) error
- func (c *Container) Reset()
- type DefaultValidator
- type DefenseConfig
- type DefensePolicy
- type ECHAnalysisResultImpl
- type ECHAnalyzerImpl
- type ECHExtensionData
- type ECHParser
- type EngineConfig
- type EntropyConfig
- type Environment
- type Error
- type ErrorCode
- type ErrorHandler
- type ErrorSeverity
- type EventResult
- type ExtensionBuilder
- func (b *ExtensionBuilder) GetAnalyzers() []Analyzer
- func (b *ExtensionBuilder) GetExtensionType() ExtensionType
- func (b *ExtensionBuilder) GetHandlers() []Handler
- func (b *ExtensionBuilder) GetParser() Parser
- func (b *ExtensionBuilder) GetTransforms() []Transform
- func (b *ExtensionBuilder) GetValidators() []Validator
- func (b *ExtensionBuilder) WithAnalyzer(analyzer Analyzer) *ExtensionBuilder
- func (b *ExtensionBuilder) WithHandler(handler Handler) *ExtensionBuilder
- func (b *ExtensionBuilder) WithParser(parser Parser) *ExtensionBuilder
- func (b *ExtensionBuilder) WithTransform(transform Transform) *ExtensionBuilder
- func (b *ExtensionBuilder) WithValidator(validator Validator) *ExtensionBuilder
- type ExtensionData
- type ExtensionEvent
- type ExtensionMetadata
- type ExtensionRegistry
- type ExtensionStatusDetail
- type ExtensionType
- type HandleStage
- type Handler
- type HandlerFactory
- type HeadlessBrowserConfig
- type Identifiable
- type Initializable
- type InputSanitizer
- type Interceptor
- type Logger
- type LoggerConfig
- type MarkerInfo
- type MobileScreenConfig
- type MobileScreenRule
- type OSPlatformConfig
- type OSRule
- type PanicHandler
- type ParseStage
- type Parser
- type ParserFactory
- type Plugin
- type PluginFactory
- type PluginInfo
- type ProcessingEngine
- type ProcessingRequest
- type ProcessingResult
- type ProcessingScenario
- type RateLimiter
- type RecoveryManager
- type RegistryDiagnostics
- func (rd *RegistryDiagnostics) CountByCategory() map[string]int
- func (rd *RegistryDiagnostics) GetDiagnosticReport() string
- func (rd *RegistryDiagnostics) GetExtensionStatus(extType ExtensionType) (*ExtensionStatusDetail, error)
- func (rd *RegistryDiagnostics) GetStatus() RegistryStatus
- func (rd *RegistryDiagnostics) HealthCheck() (healthy bool, issues []string)
- func (rd *RegistryDiagnostics) ListExtensions() []ExtensionStatusDetail
- func (rd *RegistryDiagnostics) ValidateRequiredExtensions(required []ExtensionType) (valid bool, missing []ExtensionType)
- type RegistryPort
- type RegistryStatus
- type RequestGuard
- type ResourceMonitor
- type RiskLevel
- type RulesConfig
- type RulesProvider
- type RulesScoringConfig
- type SecurityAuditor
- type SimpleLogger
- func (sl *SimpleLogger) Debug(msg string, args ...interface{})
- func (sl *SimpleLogger) Error(msg string, err error, args ...interface{})
- func (sl *SimpleLogger) Fatal(msg string, args ...interface{})
- func (sl *SimpleLogger) Info(msg string, args ...interface{})
- func (sl *SimpleLogger) SetLevel(level int)
- func (sl *SimpleLogger) Warn(msg string, args ...interface{})
- type ToolMarkersConfig
- type Transform
- type TransformFactory
- type TransformStage
- type UAFeatureConfig
- type UAFeatureRule
- type UAOSConfig
- type UARuleOS
- type ValidationResult
- type Validator
- type ValidatorConfig
- type ValidatorFactory
Constants ¶
const ( CategoryEncryption = "encryption" CategoryNegotiation = "negotiation" CategoryPreference = "preference" CategoryIdentification = "identification" CategoryCompression = "compression" CategorySecurity = "security" CategoryPerformance = "performance" CategoryCompatibility = "compatibility" CategoryExperimental = "experimental" CategoryClientHints = "client_hints" )
Standard extension categories
Variables ¶
var ( // Registry errors ErrExtensionNotFound = errors.New("extension not found") ErrExtensionNotRegistered = errors.New("extension not registered") ErrParserNotFound = errors.New("parser not found") ErrAnalyzerNotFound = errors.New("analyzer not found") ErrHandlerNotFound = errors.New("handler not found") ErrPluginNotFound = errors.New("plugin not found") // Validation errors ErrInvalidMetadata = errors.New("invalid extension metadata") ErrInvalidParser = errors.New("invalid parser") ErrInvalidAnalyzer = errors.New("invalid analyzer") ErrInvalidHandler = errors.New("invalid handler") ErrInvalidPlugin = errors.New("invalid plugin") // Processing errors ErrParseFailure = errors.New("failed to parse extension") ErrAnalysisFailure = errors.New("failed to analyze extension") ErrHandleFailure = errors.New("failed to handle extension") ErrPluginInitFailure = errors.New("failed to initialize plugin") ErrPluginValidationFailure = errors.New("plugin validation failed") // Configuration errors ErrInvalidConfig = errors.New("invalid configuration") ErrMissingConfig = errors.New("missing required configuration") )
Functions ¶
func ComparePerformance ¶
ComparePerformance is a performance comparison helper function
func Example1_BasicUsage ¶
func Example1_BasicUsage()
Example1_BasicUsage demonstrates basic ProcessWithPipeline usage
func Example2_LoggingMiddleware ¶
func Example2_LoggingMiddleware()
Example2_LoggingMiddleware demonstrates logging middleware integration
func Example3_CachingMiddleware ¶
func Example3_CachingMiddleware()
Example3_CachingMiddleware demonstrates caching middleware usage
func Example4_ABTest ¶
func Example4_ABTest()
Example4_ABTest demonstrates how to perform A/B testing
func Example5_SelectiveStrategy ¶
func Example5_SelectiveStrategy()
Example5_SelectiveStrategy demonstrates selective migration strategy
func GetRegistryStats ¶
func GetRegistryStats() map[string]interface{}
GetRegistryStats returns registry statistics
func InitializeECHExtension ¶
func InitializeECHExtension() error
InitializeECHExtension initializes ECH extension support
func LoadPlugins ¶
LoadPlugins loads all plugins from the configuration file
func RegisterAnalyzer ¶
func RegisterAnalyzer(extType ExtensionType, analyzer Analyzer) error
RegisterAnalyzer registers an extension analyzer
func RegisterAnalyzerBuilder ¶
func RegisterAnalyzerBuilder(extType ExtensionType, builder func() (Analyzer, error)) error
RegisterAnalyzerBuilder registers an analyzer builder function
func RegisterComparerBuilder ¶
RegisterComparerBuilder registers a comparer builder function
func RegisterExtension ¶
func RegisterExtension(metadata *ExtensionMetadata) error
RegisterExtension registers an extension type and its metadata
func RegisterHandler ¶
func RegisterHandler(extType ExtensionType, handler Handler) error
RegisterHandler registers an extension handler (event-driven)
func RegisterHandlerBuilder ¶
RegisterHandlerBuilder registers a handler builder function name: unique handler identifier
func RegisterParser ¶
func RegisterParser(extType ExtensionType, parser Parser) error
RegisterParser registers an extension parser
func RegisterParserBuilder ¶
func RegisterParserBuilder(extType ExtensionType, builder func() (Parser, error)) error
RegisterParserBuilder registers a parser builder function
func RegisterPlugin ¶
RegisterPlugin registers a third-party plugin
func RegisterPluginBuilder ¶
RegisterPluginBuilder registers a plugin builder function
func RegisterTransformBuilder ¶
RegisterTransformBuilder registers a transform builder function
func RegisterValidatorBuilder ¶
RegisterValidatorBuilder registers a validator builder function
func SafeExecute ¶
SafeExecute safely executes a function, catching panics If a panic occurs, it returns an error containing the panic information
func SafeExecuteWithRecovery ¶
SafeExecuteWithRecovery safely executes a function with recovery logic
func SafeParseInt ¶
SafeParseInt safely parses an integer
func ShouldUseProcessWithPipeline ¶
func ShouldUseProcessWithPipeline(scenario *ProcessingScenario) bool
ShouldUseProcessWithPipeline decides whether to use the new approach
func ShowMigrationTimeline ¶
func ShowMigrationTimeline()
ShowMigrationTimeline displays the recommended migration timeline
func WaitForCanaryCompletion ¶
func WaitForCanaryCompletion(ctx context.Context, collector *CanaryMetricsCollector, duration time.Duration)
WaitForCanaryCompletion waits for canary completion
Types ¶
type AnalysisResult ¶
type AnalysisResult interface {
// Get the analyzed extension type
GetExtensionType() ExtensionType
// Whether anomalies exist
HasAnomalies() bool
// Get anomaly details
GetAnomalies() []string
// Get risk score (0.0-1.0)
GetRiskScore() float64
// Convert to map for serialization
ToMap() map[string]interface{}
}
AnalysisResult is the general analysis result interface
type AnalyzeStage ¶
type AnalyzeStage struct {
// contains filtered or unexported fields
}
AnalyzeStage analyzes extension data
func NewAnalyzeStage ¶
func NewAnalyzeStage(registry RegistryPort) *AnalyzeStage
NewAnalyzeStage creates a new AnalyzeStage
func (*AnalyzeStage) GetDependencies ¶
func (a *AnalyzeStage) GetDependencies() []string
GetDependencies returns the required preceding stages
func (*AnalyzeStage) GetName ¶
func (a *AnalyzeStage) GetName() string
GetName returns the stage name
type Analyzer ¶
type Analyzer interface {
// Analyze analyzes extension data
// data: parsed ExtensionData
// config: analysis configuration (optional)
// Returns: analysis result, error
Analyze(data ExtensionData, config map[string]interface{}) (AnalysisResult, error)
// GetType returns the extension type this analyzer handles
GetType() ExtensionType
// GetVersion returns the analyzer version
GetVersion() string
// SupportsConfig returns the list of supported configuration keys
SupportsConfig() []string
}
Analyzer is the extension analysis interface Responsible for analyzing ExtensionData and producing AnalysisResult
func CreateAnalyzer ¶
func CreateAnalyzer(extType ExtensionType) (Analyzer, error)
CreateAnalyzer creates an analyzer instance
func GetAnalyzer ¶
func GetAnalyzer(extType ExtensionType) (Analyzer, error)
GetAnalyzer returns the extension analyzer
type AnalyzerFactory ¶
type AnalyzerFactory struct {
// contains filtered or unexported fields
}
AnalyzerFactory is the analyzer factory
type AuditConfig ¶
type AuditConfig struct {
// Whether to enable auditing
Enable bool
// Max audit events (retained in memory)
MaxEvents int
// Warning threshold
AlertThreshold int
// Block threshold
BlockThreshold int
// Audit log output target
LogOutput string
// Audit log file path
LogFilePath string
}
AuditConfig holds audit configuration
type AuditEvent ¶
type AuditEvent struct {
Timestamp time.Time
EventType string // "validation_failed", "resource_exceeded", "security_violation"
Severity string // "info", "warning", "critical"
Message string
Details map[string]interface{}
}
AuditEvent represents an audit event
type Auditable ¶
type Auditable interface {
// RecordEvent records an event
// Returns: error
RecordEvent(eventType, severity, message string, details map[string]interface{}) error
}
Auditable is the interface for auditable components
Follows Go's implicit interface design, components need not explicitly declare implementation
type CanaryConfig ¶
type CanaryConfig struct {
// Canary stage
Stage CanaryStage
// Target traffic percentage
TargetPercentage float64
// Enable canary
Enabled bool
// Canary start time
StartTime time.Time
// Canary duration (0 means no limit)
Duration time.Duration
}
CanaryConfig holds canary release configuration
type CanaryHealthCheck ¶
type CanaryHealthCheck struct {
// contains filtered or unexported fields
}
CanaryHealthCheck performs canary health checks
func NewCanaryHealthCheck ¶
func NewCanaryHealthCheck(collector *CanaryMetricsCollector) *CanaryHealthCheck
NewCanaryHealthCheck creates a canary health check
func (*CanaryHealthCheck) CheckHealth ¶
func (c *CanaryHealthCheck) CheckHealth(ctx context.Context) (healthy bool, alerts []string, critique string)
CheckHealth checks canary health status
type CanaryLifecycle ¶
type CanaryLifecycle struct {
// contains filtered or unexported fields
}
CanaryLifecycle manages the canary release lifecycle
func NewCanaryLifecycle ¶
func NewCanaryLifecycle() *CanaryLifecycle
NewCanaryLifecycle creates a canary lifecycle manager
func (*CanaryLifecycle) CanUpgrade ¶
func (c *CanaryLifecycle) CanUpgrade() bool
CanUpgrade checks whether the canary can be upgraded to the next stage
func (*CanaryLifecycle) EndStage ¶
func (c *CanaryLifecycle) EndStage() *CanaryReport
EndStage ends the current canary stage
func (*CanaryLifecycle) PrintLifecycleStatus ¶
func (c *CanaryLifecycle) PrintLifecycleStatus()
PrintLifecycleStatus prints the lifecycle status
func (*CanaryLifecycle) StartStage ¶
func (c *CanaryLifecycle) StartStage(stage CanaryStage, duration time.Duration)
StartStage starts a new canary stage
type CanaryMetrics ¶
type CanaryMetrics struct {
// Basic metrics
TotalRequests int64
NewMethodRequests int64
OldMethodRequests int64
SuccessfulRequests int64
FailedRequests int64
// Latency metrics
TotalLatency time.Duration
MinLatency time.Duration
MaxLatency time.Duration
AvgLatency time.Duration
P50Latency time.Duration
P95Latency time.Duration
P99Latency time.Duration
// Cache metrics
CacheHits int64
CacheMisses int64
CacheHitRate float64
// Error metrics
ErrorCount int64
ErrorRate float64
// Resource metrics
MemoryUsage int64
GCTime time.Duration
// Timestamps
CollectedAt time.Time
}
CanaryMetrics holds canary release metrics
type CanaryMetricsCollector ¶
type CanaryMetricsCollector struct {
// contains filtered or unexported fields
}
CanaryMetricsCollector collects canary release metrics
func NewCanaryMetricsCollector ¶
func NewCanaryMetricsCollector(config *CanaryConfig) *CanaryMetricsCollector
NewCanaryMetricsCollector creates a canary metrics collector
func (*CanaryMetricsCollector) DisableCanary ¶
func (c *CanaryMetricsCollector) DisableCanary()
DisableCanary disables canary release
func (*CanaryMetricsCollector) EnableCanary ¶
func (c *CanaryMetricsCollector) EnableCanary(stage CanaryStage, percentage float64, duration time.Duration)
EnableCanary enables canary release
func (*CanaryMetricsCollector) GenerateCanaryReport ¶
func (c *CanaryMetricsCollector) GenerateCanaryReport(startTime time.Time) *CanaryReport
GenerateCanaryReport generates a canary report
func (*CanaryMetricsCollector) GetCurrentMetrics ¶
func (c *CanaryMetricsCollector) GetCurrentMetrics() *CanaryMetrics
GetCurrentMetrics returns the current metrics
func (*CanaryMetricsCollector) GetMetricsHistory ¶
func (c *CanaryMetricsCollector) GetMetricsHistory(hours int) []*CanaryMetrics
GetMetricsHistory returns the metrics history
func (*CanaryMetricsCollector) RecordCacheHit ¶
func (c *CanaryMetricsCollector) RecordCacheHit(hit bool)
RecordCacheHit records a cache hit
func (*CanaryMetricsCollector) RecordRequest ¶
func (c *CanaryMetricsCollector) RecordRequest(requestID string, useNewMethod bool, duration time.Duration, success bool)
RecordRequest records a request
func (*CanaryMetricsCollector) SnapshotMetrics ¶
func (c *CanaryMetricsCollector) SnapshotMetrics()
SnapshotMetrics saves a metrics snapshot (for historical analysis)
type CanaryReport ¶
type CanaryReport struct {
Stage CanaryStage
Duration time.Duration
StartTime time.Time
EndTime time.Time
// Traffic distribution
TotalRequests int64
NewMethodRequests int64
OldMethodRequests int64
NewMethodPercent float64
// Success rate
SuccessRate float64
ErrorRate float64
// Latency comparison
NewMethodAvgLatency time.Duration
OldMethodAvgLatency time.Duration
LatencyDifference float64 // percentage
// Cache effectiveness
CacheHitRate float64
// Result consistency
Consistency float64 // 0-1
// Recommendation
Recommendation string
}
func (*CanaryReport) Print ¶
func (report *CanaryReport) Print()
PrintCanaryReport prints the canary report
type CanaryRouter ¶
type CanaryRouter struct {
// contains filtered or unexported fields
}
CanaryRouter routes canary traffic
func (*CanaryRouter) ShouldUseNewMethod ¶
func (r *CanaryRouter) ShouldUseNewMethod(requestID string) bool
ShouldUseNewMethod determines whether to use the new method
type CanaryStage ¶
type CanaryStage string
CanaryStage represents a canary release stage
const ( CanaryStage5Percent CanaryStage = "5%" CanaryStage25Percent CanaryStage = "25%" CanaryStage50Percent CanaryStage = "50%" CanaryStage100Percent CanaryStage = "100%" )
type CanaryThresholds ¶
type CanaryThresholds struct {
// Alert thresholds
MaxErrorRate float64
MaxP99Latency time.Duration
MinCacheHitRate float64
MaxMemoryGrowth int64 // bytes/minute
// Rollback trigger thresholds
CriticalErrorRate float64
CriticalP99Latency time.Duration
}
CanaryThresholds defines canary thresholds
func DefaultCanaryThresholds ¶
func DefaultCanaryThresholds() *CanaryThresholds
DefaultCanaryThresholds returns default canary thresholds
type Closeable ¶
type Closeable interface {
// Close closes the component and releases resources
Close() error
}
Closeable is the interface for components that support resource cleanup
Any component that needs to release resources can implement this interface Consistent with io.Closer for ease of use
type Comparer ¶
type Comparer interface {
// Compare compares two data sets
// data1, data2: data to compare
// Returns: similarity (0.0-1.0), list of differences
Compare(data1, data2 interface{}) (float64, []string, error)
// GetName returns the comparer name
GetName() string
}
ComparerComparable protocol for extension data comparison Used for comparison and difference detection between extensions
func CreateComparer ¶
CreateComparer creates a comparer instance
type ComparerFactory ¶
type ComparerFactory struct {
// contains filtered or unexported fields
}
ComparerFactory is the comparer factory
type Component ¶
type Component interface {
// GetInfo returns component information
GetInfo() ComponentInfo
}
Component is the base interface for all governable components
Follows the single responsibility principle, each component defines only minimal necessary behavior Concrete components can extend functionality through composition
Usage example:
var comp Component = myParser info := comp.GetInfo()
type ComponentInfo ¶
type ComponentInfo struct {
// Component name
Name string
// Component version
Version string
// Component description
Description string
// Component author
Author string
}
ComponentInfo holds component information
type Config ¶
type Config struct {
// Runtime environment
Environment Environment
// Defense configuration
Defense *DefensePolicy
// Logger configuration
Logger *LoggerConfig
// Validation configuration
Validator *ValidatorConfig
// Audit configuration
Audit *AuditConfig
// Rules configuration
Rules *RulesConfig
// Rules configuration source (file path or filename)
RulesSource string
}
Config is the unified configuration object that manages all module configurations
Usage example:
config := NewConfig(EnvProduction) config.Defense.MaxInputSize = 4096 config.Logger.Level = 2
Environment variable support:
FINGERPRINT_ENV - Runtime environment (development/testing/production) FINGERPRINT_LOG_LEVEL - Log level (0-4) FINGERPRINT_MAX_INPUT_SIZE - Max input size (bytes)
func NewConfig ¶
func NewConfig(env Environment) *Config
NewConfig creates a configuration object, applying presets based on environment
func NewConfigFromEnv ¶
func NewConfigFromEnv() *Config
NewConfigFromEnv creates a configuration from environment variables
func NewUnifiedConfigFromEnv ¶
func NewUnifiedConfigFromEnv() *Config
NewUnifiedConfigFromEnv creates a unified configuration from environment variables This entry point loads both:
- extension runtime configuration (Defense/Logger/Validator/Audit)
- rules configuration (internal/config/rules.json)
Environment variables:
- FINGERPRINT_RULES_PATH: absolute/relative path to rules configuration
- FINGERPRINT_RULES_FILE: rules configuration filename (for searching by candidate paths)
func (*Config) LoadRulesByFilename ¶
LoadRulesByFilename loads rules configuration by filename and applies overrides
func (*Config) LoadRulesFromPath ¶
LoadRulesFromPath loads rules configuration from the specified path and applies overrides
type ConfigProvider ¶
type ConfigProvider interface {
NewConfigFromEnv() *Config
}
ConfigProvider is the runtime configuration provider port
type Container ¶
type Container struct {
// contains filtered or unexported fields
}
Container is the dependency injection container that manages the lifecycle and dependencies of all components
Usage example:
config := NewConfig(EnvProduction)
container := NewContainer(config)
logger, err := container.GetLogger("myapp")
guard, err := container.GetRequestGuard()
validator, err := container.GetValidator()
Features:
- Singleton pattern: each component is created only once
- Lazy loading: components are created on first use
- Thread-safe: uses mutexes to protect shared state
func NewContainer ¶
NewContainer creates a dependency injection container
func (*Container) GetLogger ¶
func (c *Container) GetLogger(name string) (*SimpleLogger, error)
GetLogger returns the logger instance
func (*Container) GetRateLimiter ¶
func (c *Container) GetRateLimiter() (*RateLimiter, error)
GetRateLimiter returns the rate limiter instance
func (*Container) GetRequestGuard ¶
func (c *Container) GetRequestGuard() (*RequestGuard, error)
GetRequestGuard returns the request guard instance
func (*Container) GetSecurityAuditor ¶
func (c *Container) GetSecurityAuditor() (*SecurityAuditor, error)
GetSecurityAuditor returns the security auditor instance
func (*Container) GetValidator ¶
func (c *Container) GetValidator() (*DefaultValidator, error)
GetValidator returns the validator instance
func (*Container) Initialize ¶
Initialize initializes all default components in the container Pre-loads critical components to improve startup performance
type DefaultValidator ¶
type DefaultValidator struct {
// Max data size (bytes)
MaxDataSize int
// Max extensions
MaxExtensions int
// Enable strict mode
StrictMode bool
}
DefaultValidator is the default input validator
Usage example:
validator := extension.NewDefaultValidator()
validator.MaxDataSize = 8192 // 8KB
validator.StrictMode = true
if err := validator.ValidateData(data); err != nil {
return err
}
if err := validator.ValidateMetadata(metadata); err != nil {
return err
}
Validation items:
- Data is non-empty and does not exceed MaxDataSize
- Metadata required fields (Type, Name)
- Metadata field size limits (Name ≤256B, Description ≤1KB)
- Configuration item size limits (max 1000 keys)
func NewDefaultValidator ¶
func NewDefaultValidator() *DefaultValidator
NewDefaultValidator creates a default validator
func (*DefaultValidator) ValidateConfig ¶
func (v *DefaultValidator) ValidateConfig(config map[string]interface{}) error
ValidateConfig validates configuration
func (*DefaultValidator) ValidateData ¶
func (v *DefaultValidator) ValidateData(data []byte) error
ValidateData validates extension data
func (*DefaultValidator) ValidateMetadata ¶
func (v *DefaultValidator) ValidateMetadata(metadata *ExtensionMetadata) error
ValidateMetadata validates metadata
type DefenseConfig ¶
type DefenseConfig struct {
// contains filtered or unexported fields
}
DefenseConfig is the defense configuration helper
func NewDefenseConfig ¶
func NewDefenseConfig() *DefenseConfig
NewDefenseConfig creates a defense configuration
func (*DefenseConfig) GetGuard ¶
func (dc *DefenseConfig) GetGuard(name string) (*RequestGuard, error)
GetGuard retrieves a guard
func (*DefenseConfig) RegisterGuard ¶
func (dc *DefenseConfig) RegisterGuard(name string, policy *DefensePolicy) error
RegisterGuard registers a guard
type DefensePolicy ¶
type DefensePolicy struct {
// Input checks
ValidateInput bool
MaxInputSize int
// Resource limits
LimitMemory bool
MaxMemoryMB int
// Timeout settings
EnableTimeout bool
TimeoutSec int
// Rate limit
EnableRateLimit bool
RateLimit int // requests per minute
// Strict mode
StrictMode bool
}
DefensePolicy holds defense policy configuration
Usage example (default policy):
policy := extension.DefaultDefensePolicy()
guard := extension.NewRequestGuard(policy)
if err := guard.ValidateRequest(request); err != nil {
return err
}
Custom strict policy:
policy := &extension.DefensePolicy{
ValidateInput: true,
MaxInputSize: 4096, // 4KB
LimitMemory: true,
MaxMemoryMB: 256,
EnableTimeout: true,
TimeoutSec: 10,
EnableRateLimit: true,
RateLimit: 500, // 500 req/min
StrictMode: true,
}
Default values (recommended):
MaxInputSize: 65536 (64KB) MaxMemoryMB: 256 TimeoutSec: 30 RateLimit: 1000 (1000 req/min)
func DefaultDefensePolicy ¶
func DefaultDefensePolicy() *DefensePolicy
DefaultDefensePolicy returns the default defense policy
type ECHAnalysisResultImpl ¶
type ECHAnalysisResultImpl struct {
ExtType ExtensionType
Present bool
ECHType string // outer, inner, grease
Version uint16
RiskScore float64
Anomalies []string
VisibleFields map[string]interface{}
Metadata map[string]interface{}
}
ECHAnalysisResultImpl is the ECH analysis result implementation
func (*ECHAnalysisResultImpl) GetAnomalies ¶
func (r *ECHAnalysisResultImpl) GetAnomalies() []string
func (*ECHAnalysisResultImpl) GetExtensionType ¶
func (r *ECHAnalysisResultImpl) GetExtensionType() ExtensionType
func (*ECHAnalysisResultImpl) GetRiskScore ¶
func (r *ECHAnalysisResultImpl) GetRiskScore() float64
func (*ECHAnalysisResultImpl) HasAnomalies ¶
func (r *ECHAnalysisResultImpl) HasAnomalies() bool
func (*ECHAnalysisResultImpl) ToMap ¶
func (r *ECHAnalysisResultImpl) ToMap() map[string]interface{}
type ECHAnalyzerImpl ¶
type ECHAnalyzerImpl struct {
// contains filtered or unexported fields
}
ECHAnalyzerImpl is the new ECH analyzer implementation
func NewECHAnalyzerImpl ¶
func NewECHAnalyzerImpl() *ECHAnalyzerImpl
func (*ECHAnalyzerImpl) Analyze ¶
func (a *ECHAnalyzerImpl) Analyze(data ExtensionData, config map[string]interface{}) (AnalysisResult, error)
func (*ECHAnalyzerImpl) GetType ¶
func (a *ECHAnalyzerImpl) GetType() ExtensionType
func (*ECHAnalyzerImpl) GetVersion ¶
func (a *ECHAnalyzerImpl) GetVersion() string
func (*ECHAnalyzerImpl) SupportsConfig ¶
func (a *ECHAnalyzerImpl) SupportsConfig() []string
type ECHExtensionData ¶
type ECHExtensionData struct {
Type ExtensionType
Version uint16
ConfigID uint8
RawData []byte
EncryptedData []byte
ClientHelloData map[string]interface{}
}
ECHExtensionData represents the ECH extension data structure
func (*ECHExtensionData) GetName ¶
func (e *ECHExtensionData) GetName() string
func (*ECHExtensionData) GetRawData ¶
func (e *ECHExtensionData) GetRawData() []byte
func (*ECHExtensionData) GetType ¶
func (e *ECHExtensionData) GetType() ExtensionType
func (*ECHExtensionData) ToMap ¶
func (e *ECHExtensionData) ToMap() map[string]interface{}
type ECHParser ¶
type ECHParser struct {
// contains filtered or unexported fields
}
ECHParser is the new ECH parser implementation
func NewECHParser ¶
func NewECHParser() *ECHParser
func (*ECHParser) GetType ¶
func (p *ECHParser) GetType() ExtensionType
func (*ECHParser) GetVersion ¶
type EngineConfig ¶
type EngineConfig struct {
// Whether to enable concurrent processing
ConcurrentProcessing bool
// Maximum concurrency
MaxConcurrency int
// Whether to enable caching
EnableCaching bool
// Cache size
CacheSize int
// Processing timeout (milliseconds)
TimeoutMs int
// Whether to enable strict validation
StrictValidation bool
// Whether to enable verbose logging
VerboseLogging bool
// Custom configuration
CustomConfig map[string]interface{}
}
EngineConfig holds engine configuration
type EntropyConfig ¶
type EntropyConfig struct {
Enabled bool `json:"enabled"`
HighThreshold float64 `json:"high_threshold"`
LowThreshold int `json:"low_threshold"`
Description string `json:"description"`
Sensitivity string `json:"sensitivity"`
}
EntropyConfig holds entropy configuration
type Environment ¶
type Environment string
Environment represents the runtime environment enum
const ( EnvDevelopment Environment = "development" EnvTesting Environment = "testing" EnvProduction Environment = "production" )
type Error ¶
type Error struct {
Code ErrorCode
Message string
Cause error
Context map[string]interface{}
Severity ErrorSeverity
Timestamp int64
}
Error is the standard error type for the extension system
Field descriptions:
Code - Error code for classification and integration Message - Human-readable error description Cause - Original error, supports error chaining Context - Error context key-value pairs (for debugging) Severity - Error severity level (determines recoverability) Timestamp - Time when the error occurred
Usage example:
// Create error
err := extension.NewError(
extension.ErrCodeInvalidInput,
"invalid user input",
)
// Add context information (for debugging)
err = err.WithContext("user_id", 12345)
err = err.WithContext("field", "email")
err = err.WithContext("value", userEmail)
// Determine error type
if err.IsRecoverable() {
// Info, Warning, Error level errors are recoverable
return retryOperation()
}
if err.IsFatal() {
// Fatal level errors are non-recoverable
return err
}
Creation variants:
extension.NewError(code, message) // Standard error extension.NewErrorWithCause(code, message, cause) // Error with cause extension.NewFatalError(code, message) // Fatal error extension.NewWarning(message) // Warning (no code needed)
Error chaining:
err := processData(data)
if err != nil {
return extension.NewErrorWithCause(
extension.ErrCodeAnalysisFailed,
"analysis failed",
err, // original error as the next in the chain
)
}
func NewErrorWithCause ¶
NewErrorWithCause creates an error with a cause
func NewFatalError ¶
NewFatalError creates a fatal error
func (*Error) IsRecoverable ¶
IsRecoverable determines whether the error is recoverable
func (*Error) WithContext ¶
WithContext adds context information
type ErrorCode ¶
type ErrorCode int
ErrorCode represents an error code (for system integration and error classification)
type ErrorHandler ¶
type ErrorHandler interface {
// Handle the error
Handle(err *Error) error
// Determine whether this error can be handled
CanHandle(err *Error) bool
// Get handler name
GetName() string
}
ErrorHandler is the error handler interface
type ErrorSeverity ¶
type ErrorSeverity int
ErrorSeverity represents error severity level
const ( SeverityInfo ErrorSeverity = iota SeverityWarning SeverityError SeverityCritical SeverityFatal )
func (ErrorSeverity) String ¶
func (es ErrorSeverity) String() string
String implements the Stringer interface
type EventResult ¶
type EventResult struct {
// Whether handling was successful
Success bool
// Error message
Error string
// Handling result data
Result interface{}
// Whether to continue passing to the next handler
ContinueProcessing bool
// Handler name
HandlerName string
}
EventResult holds event handling results
type ExtensionBuilder ¶
type ExtensionBuilder struct {
// contains filtered or unexported fields
}
ExtensionBuilder is the general-purpose extension builder Combines all factories to build a complete extension processing pipeline
func NewExtensionBuilder ¶
func NewExtensionBuilder(extType ExtensionType) *ExtensionBuilder
NewExtensionBuilder creates an extension builder
func (*ExtensionBuilder) GetAnalyzers ¶
func (b *ExtensionBuilder) GetAnalyzers() []Analyzer
GetAnalyzers returns all analyzers
func (*ExtensionBuilder) GetExtensionType ¶
func (b *ExtensionBuilder) GetExtensionType() ExtensionType
GetExtensionType returns the extension type
func (*ExtensionBuilder) GetHandlers ¶
func (b *ExtensionBuilder) GetHandlers() []Handler
GetHandlers returns all handlers
func (*ExtensionBuilder) GetParser ¶
func (b *ExtensionBuilder) GetParser() Parser
GetParser returns the parser
func (*ExtensionBuilder) GetTransforms ¶
func (b *ExtensionBuilder) GetTransforms() []Transform
GetTransforms returns all transforms
func (*ExtensionBuilder) GetValidators ¶
func (b *ExtensionBuilder) GetValidators() []Validator
GetValidators returns all validators
func (*ExtensionBuilder) WithAnalyzer ¶
func (b *ExtensionBuilder) WithAnalyzer(analyzer Analyzer) *ExtensionBuilder
WithAnalyzer adds an analyzer
func (*ExtensionBuilder) WithHandler ¶
func (b *ExtensionBuilder) WithHandler(handler Handler) *ExtensionBuilder
WithHandler adds a handler
func (*ExtensionBuilder) WithParser ¶
func (b *ExtensionBuilder) WithParser(parser Parser) *ExtensionBuilder
WithParser sets the parser
func (*ExtensionBuilder) WithTransform ¶
func (b *ExtensionBuilder) WithTransform(transform Transform) *ExtensionBuilder
WithTransform adds a transform
func (*ExtensionBuilder) WithValidator ¶
func (b *ExtensionBuilder) WithValidator(validator Validator) *ExtensionBuilder
WithValidator adds a validator
type ExtensionData ¶
type ExtensionData interface {
// Get extension type
GetType() ExtensionType
// Get raw byte data
GetRawData() []byte
// Get extension name
GetName() string
// Convert to map for serialization
ToMap() map[string]interface{}
}
ExtensionData is the extension data interface
type ExtensionEvent ¶
type ExtensionEvent struct {
// Event type
Type string // "parse", "analyze", "transform"
// Extension type
ExtensionType ExtensionType
// Event data
Data interface{}
// Context at the time of the event
Context context.Context
// Event metadata
Metadata map[string]interface{}
// Timestamp
Timestamp int64
}
ExtensionEvent represents an extension event
type ExtensionMetadata ¶
type ExtensionMetadata struct {
// Extension type ID
Type ExtensionType
// Extension name (e.g. "Encrypted Client Hello")
Name string
// Extension description
Description string
// RFC document reference
RFC string
// IANA registration number
IANANumber uint16
// Last update time
LastUpdated string
// Extension category (e.g. "encryption", "negotiation", "preference")
Category string
// Whether this is an experimental extension
IsExperimental bool
// Compatible TLS versions
CompatibleTLSVersions []uint16
}
ExtensionMetadata holds extension metadata
func GetMetadata ¶
func GetMetadata(extType ExtensionType) (*ExtensionMetadata, error)
GetMetadata returns extension metadata
func ListAllExtensions ¶
func ListAllExtensions() []*ExtensionMetadata
ListAllExtensions lists all registered extensions
type ExtensionRegistry ¶
type ExtensionRegistry struct {
// contains filtered or unexported fields
}
ExtensionRegistry is the global extension registry
func GetRegistry ¶
func GetRegistry() *ExtensionRegistry
GetRegistry returns the global registry instance
type ExtensionStatusDetail ¶
type ExtensionStatusDetail struct {
Type ExtensionType
Name string
Category string
HasParser bool
HasAnalyzer bool
HandlersCount int
IsExperimental bool
RFC string
}
ExtensionStatusDetail holds extension status details
type ExtensionType ¶
type ExtensionType uint16
ExtensionType defines the extension type
const ( // TLS 1.3 Extensions ExtensionServerName ExtensionType = 0x0000 ExtensionMaxFragmentLength ExtensionType = 0x0001 ExtensionClientCertificateType ExtensionType = 0x0009 ExtensionSupportedGroups ExtensionType = 0x000a ExtensionECPointFormats ExtensionType = 0x000b ExtensionSignatureAlgorithms ExtensionType = 0x000d ExtensionUseSignatureAlgorithm ExtensionType = 0x0010 ExtensionApplicationLayerProtocol ExtensionType = 0x0010 ExtensionStatus ExtensionType = 0x0005 ExtensionSupportedVersions ExtensionType = 0x002b ExtensionPSKKeyExchangeModes ExtensionType = 0x002d ExtensionCertificateAuthorities ExtensionType = 0x002f ExtensionOIDFilters ExtensionType = 0x0030 ExtensionPostHandshakeAuth ExtensionType = 0x0031 ExtensionSignatureAlgorithmsCert ExtensionType = 0x0032 // Client Hints ExtensionSecCHUA ExtensionType = 0xfd01 ExtensionSecCHUAMobile ExtensionType = 0xfd02 ExtensionSecCHUAPlatform ExtensionType = 0xfd03 ExtensionSecCHUAPlatformVersion ExtensionType = 0xfd04 ExtensionSecCHUAModelVersion ExtensionType = 0xfd05 // Encrypted Client Hello (ECH) ExtensionEncryptedClientHello ExtensionType = 0xfe0d // ECH Outer Extensions ExtensionECHOuterExtensions ExtensionType = 0xfd00 // GREASE Extensions (Generic unsupported extension) ExtensionGREASE ExtensionType = 0x0a0a // Padding (TLS 1.3) ExtensionPadding ExtensionType = 0x0015 ExtensionPreSharedKey ExtensionType = 0x0029 // Certificate List ExtensionCertificateList ExtensionType = 0x0000 // Unknown/Custom ExtensionCustom ExtensionType = 0xffff )
Standard extension type constants
func FindExtensionByName ¶
func FindExtensionByName(name string) (ExtensionType, error)
FindExtensionByName finds an extension by name
type HandleStage ¶
type HandleStage struct {
// contains filtered or unexported fields
}
HandleStage handles extension events
func NewHandleStage ¶
func NewHandleStage(registry RegistryPort) *HandleStage
NewHandleStage creates a new HandleStage
func (*HandleStage) GetDependencies ¶
func (h *HandleStage) GetDependencies() []string
GetDependencies returns the required preceding stages
type Handler ¶
type Handler interface {
// Handle handles an extension event
// event: extension event
// Returns: handling result, error
Handle(event *ExtensionEvent) (*EventResult, error)
// GetType returns the extension type this handler handles
GetType() ExtensionType
// GetPriority returns handler priority (higher priority executes first)
// 0-100, default 50
GetPriority() int
// GetName returns the handler name
GetName() string
}
Handler is the extension handling interface Event-driven extension handling for streaming and middleware
func CreateHandler ¶
CreateHandler creates a handler instance
func GetHandlers ¶
func GetHandlers(extType ExtensionType) []Handler
GetHandlers returns extension handlers
type HandlerFactory ¶
type HandlerFactory struct {
// contains filtered or unexported fields
}
HandlerFactory is the handler factory
type HeadlessBrowserConfig ¶
type HeadlessBrowserConfig struct {
Enabled bool `json:"enabled"`
Markers []string `json:"markers"`
Description string `json:"description"`
}
HeadlessBrowserConfig holds headless browser configuration
type Identifiable ¶
type Identifiable interface {
// GetID returns the unique identifier
GetID() string
}
Identifiable is the interface for identifiable components
Any object with a unique identifier should implement this interface
type Initializable ¶
type Initializable interface {
// Initialize initializes the component
// config: initialization configuration
// Returns: error
Initialize(config map[string]interface{}) error
// IsInitialized checks whether the component is initialized
IsInitialized() bool
}
Initializable is the interface for components that support initialization
Used for lazy initialization and complex setup processes
type InputSanitizer ¶
type InputSanitizer struct {
// contains filtered or unexported fields
}
InputSanitizer is the input sanitizer
func NewInputSanitizer ¶
func NewInputSanitizer() *InputSanitizer
NewInputSanitizer creates an input sanitizer
func (*InputSanitizer) SanitizeBytes ¶
func (is *InputSanitizer) SanitizeBytes(b []byte, maxLen int) ([]byte, error)
SanitizeBytes sanitizes a byte slice
func (*InputSanitizer) SanitizeString ¶
func (is *InputSanitizer) SanitizeString(s string) (string, error)
SanitizeString sanitizes a string
type Interceptor ¶
type Interceptor interface {
// Intercept handles interception
// phase: processing phase (pre, post)
// request: processing request
// result: processing result (valid in post phase)
Intercept(phase string, request *ProcessingRequest, result *ProcessingResult) error
}
Interceptor is the interceptor interface Used to insert custom logic into the processing workflow
type Logger ¶
type Logger interface {
// Log info
Info(msg string, args ...interface{})
// Log warning
Warn(msg string, args ...interface{})
// Log error
Error(msg string, err error, args ...interface{})
// Log debug
Debug(msg string, args ...interface{})
// Log panic
Fatal(msg string, args ...interface{})
}
Logger is the logging interface
type LoggerConfig ¶
type LoggerConfig struct {
// Log level (0=debug, 1=info, 2=warn, 3=error, 4=fatal)
Level int
// Log output target
// "stdout", "stderr", "file"
Output string
// Log file path (only effective when Output="file")
FilePath string
// Whether to enable structured logging
Structured bool
// Log format
// "text", "json"
Format string
}
LoggerConfig holds logger configuration
type MarkerInfo ¶
type MarkerInfo struct {
Marker string `json:"marker"`
Type string `json:"type"`
Severity string `json:"severity"`
}
MarkerInfo holds information for a single marker
type MobileScreenConfig ¶
type MobileScreenConfig struct {
Enabled bool `json:"enabled"`
MobileScreenWidthMax int `json:"mobile_screen_width_max"`
DesktopScreenWidthMin int `json:"desktop_screen_width_min"`
Description string `json:"description"`
Rules []MobileScreenRule `json:"rules"`
}
MobileScreenConfig holds mobile screen configuration
type MobileScreenRule ¶
type MobileScreenRule struct {
Device string `json:"device"`
ScreenWidthThreshold int `json:"screen_width_threshold"`
Rule string `json:"rule"`
}
MobileScreenRule represents a mobile screen rule
type OSPlatformConfig ¶
type OSPlatformConfig struct {
Enabled bool `json:"enabled"`
Rules []OSRule `json:"rules"`
Description string `json:"description"`
}
OSPlatformConfig holds OS/Platform contradiction configuration
type OSRule ¶
type OSRule struct {
OS string `json:"os"`
PlatformMustContain interface{} `json:"platform_must_contain"`
Severity string `json:"severity"`
}
OSRule represents an OS rule
type PanicHandler ¶
type PanicHandler struct {
// contains filtered or unexported fields
}
PanicHandler is the panic recovery handler
func NewPanicHandler ¶
func NewPanicHandler() *PanicHandler
func (*PanicHandler) CanHandle ¶
func (ph *PanicHandler) CanHandle(err *Error) bool
func (*PanicHandler) GetName ¶
func (ph *PanicHandler) GetName() string
func (*PanicHandler) Handle ¶
func (ph *PanicHandler) Handle(err *Error) error
type ParseStage ¶
type ParseStage struct {
// contains filtered or unexported fields
}
ParseStage parses extension data (from raw TLS data into structured format)
func NewParseStage ¶
func NewParseStage(registry RegistryPort) *ParseStage
NewParseStage creates a new ParseStage
func (*ParseStage) GetDependencies ¶
func (p *ParseStage) GetDependencies() []string
GetDependencies returns the required preceding stages
type Parser ¶
type Parser interface {
// Parse parses extension data
// data: raw extension data (excluding extension header)
// parentContext: parent context (e.g. complete ClientHello)
// Returns: parsed ExtensionData, error
Parse(data []byte, parentContext context.Context) (ExtensionData, error)
// GetType returns the extension type this parser handles
GetType() ExtensionType
// GetVersion returns the parser version
GetVersion() string
}
Parser is the extension parsing interface Responsible for parsing raw byte data into structured ExtensionData
func CreateParser ¶
func CreateParser(extType ExtensionType) (Parser, error)
CreateParser creates a parser instance
func GetParser ¶
func GetParser(extType ExtensionType) (Parser, error)
GetParser returns the extension parser
type ParserFactory ¶
type ParserFactory struct {
// contains filtered or unexported fields
}
ParserFactory is the parser factory
type Plugin ¶
type Plugin interface {
// GetInfo returns plugin information
GetInfo() *PluginInfo
// Init initializes the plugin
// config: plugin configuration
// Returns: error
Init(config map[string]interface{}) error
// Register registers the plugin's extensions
// This method should call RegisterExtension, RegisterParser, etc.
Register() error
// Unload unloads the plugin
Unload() error
// Validate validates plugin validity
Validate() error
// GetDependencies returns the plugin dependency list
GetDependencies() []string
// GetVersion returns the plugin version
GetVersion() string
}
Plugin is the third-party plugin interface Allows external developers to extend fingerprint library functionality
func CreatePlugin ¶
CreatePlugin creates a plugin instance
type PluginFactory ¶
type PluginFactory struct {
// contains filtered or unexported fields
}
PluginFactory is the plugin factory
type PluginInfo ¶
type PluginInfo struct {
// Plugin ID (unique identifier)
ID string
// Plugin name
Name string
// Plugin description
Description string
// Plugin version
Version string
// Author
Author string
// Contact information
Contact string
// License
License string
// Homepage
Homepage string
// Minimum SDK version
MinSDKVersion string
// Maximum SDK version
MaxSDKVersion string
}
PluginInfo holds plugin information
type ProcessingEngine ¶
type ProcessingEngine struct {
// contains filtered or unexported fields
}
ProcessingEngine is the extension processing engine Coordinates parsing, analysis, transformation, and processing workflows
func NewProcessingEngine ¶
func NewProcessingEngine(config *EngineConfig) *ProcessingEngine
NewProcessingEngine creates a processing engine
func (*ProcessingEngine) GetConfig ¶
func (e *ProcessingEngine) GetConfig() *EngineConfig
GetConfig returns the engine configuration
func (*ProcessingEngine) Process ¶
func (e *ProcessingEngine) Process(request *ProcessingRequest) *ProcessingResult
Process processes an extension request
func (*ProcessingEngine) RegisterInterceptor ¶
func (e *ProcessingEngine) RegisterInterceptor(phase string, interceptor Interceptor) error
RegisterInterceptor registers an interceptor phase: pre or post
func (*ProcessingEngine) SetConfig ¶
func (e *ProcessingEngine) SetConfig(config *EngineConfig) error
SetConfig sets the engine configuration
type ProcessingRequest ¶
type ProcessingRequest struct {
// Extension type
ExtensionType ExtensionType
// Raw extension data
RawData []byte
// Processing steps (parse, analyze, transform)
Steps []string
// Analysis configuration
AnalysisConfig map[string]interface{}
// Context information
Context context.Context
// Request metadata
Metadata map[string]interface{}
}
ProcessingRequest represents a processing request
type ProcessingResult ¶
type ProcessingResult struct {
// Request ID
RequestID string
// Whether successful
Success bool
// Error message
Error string
// Parse result
ParsedData ExtensionData
// Analysis results list
AnalysisResults []AnalysisResult
// Processing events list
Events []*ExtensionEvent
// Processing elapsed time (milliseconds)
ElapsedMs int64
// Result metadata
Metadata map[string]interface{}
}
ProcessingResult holds processing results
type ProcessingScenario ¶
type ProcessingScenario struct {
NeedsDetailedLogging bool
NeedsDistributedTracing bool
NeedsMetrics bool
IsHighConcurrencyPath bool
CanTolerateLatency bool
NeedsCaching bool
IsUltraPerformanceSensitive bool
}
ProcessingScenario describes a processing scenario
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter is a rate limiter that prevents request flooding
Usage example:
limiter := extension.NewRateLimiter(100, time.Minute)
if err := limiter.Allow(); err != nil {
return err // rate limit exceeded
}
// process the request
How it works: token bucket algorithm
- Allows maxRequests requests per time window
- Returns ErrCodeResourceExhausted when exceeded
- Uses mutex to ensure thread safety
func NewRateLimiter ¶
func NewRateLimiter(maxRequests int, timeWindow time.Duration) *RateLimiter
NewRateLimiter creates a rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow() error
Allow checks whether a request is allowed
type RecoveryManager ¶
type RecoveryManager struct {
// contains filtered or unexported fields
}
RecoveryManager is the recovery manager
func NewRecoveryManager ¶
func NewRecoveryManager(logger Logger) *RecoveryManager
NewRecoveryManager creates a recovery manager
func (*RecoveryManager) Handle ¶
func (rm *RecoveryManager) Handle(err error) error
Handle handles an error
func (*RecoveryManager) IsRecoverable ¶
func (rm *RecoveryManager) IsRecoverable(err error) bool
IsRecoverable determines whether an error is recoverable
func (*RecoveryManager) RegisterHandler ¶
func (rm *RecoveryManager) RegisterHandler(handler ErrorHandler) error
RegisterHandler registers an error handler
type RegistryDiagnostics ¶
type RegistryDiagnostics struct {
// contains filtered or unexported fields
}
RegistryDiagnostics is the extension registry diagnostics tool
func NewRegistryDiagnostics ¶
func NewRegistryDiagnostics(registry *ExtensionRegistry) *RegistryDiagnostics
NewRegistryDiagnostics creates a diagnostics tool
func (*RegistryDiagnostics) CountByCategory ¶
func (rd *RegistryDiagnostics) CountByCategory() map[string]int
CountByCategory counts extensions by category
func (*RegistryDiagnostics) GetDiagnosticReport ¶
func (rd *RegistryDiagnostics) GetDiagnosticReport() string
GetDiagnosticReport returns the complete diagnostic report (text format)
func (*RegistryDiagnostics) GetExtensionStatus ¶
func (rd *RegistryDiagnostics) GetExtensionStatus(extType ExtensionType) (*ExtensionStatusDetail, error)
GetExtensionStatus returns the detailed status of a specific extension
func (*RegistryDiagnostics) GetStatus ¶
func (rd *RegistryDiagnostics) GetStatus() RegistryStatus
GetStatus returns the complete status snapshot of the current registry
func (*RegistryDiagnostics) HealthCheck ¶
func (rd *RegistryDiagnostics) HealthCheck() (healthy bool, issues []string)
HealthCheck performs a health check and returns any issues found
func (*RegistryDiagnostics) ListExtensions ¶
func (rd *RegistryDiagnostics) ListExtensions() []ExtensionStatusDetail
ListExtensions returns a list of all registered extensions
func (*RegistryDiagnostics) ValidateRequiredExtensions ¶
func (rd *RegistryDiagnostics) ValidateRequiredExtensions(required []ExtensionType) (valid bool, missing []ExtensionType)
ValidateRequiredExtensions validates whether required extensions are loaded
type RegistryPort ¶
type RegistryPort interface {
GetParser(extType ExtensionType) (Parser, error)
GetAnalyzer(extType ExtensionType) (Analyzer, error)
GetHandlers(extType ExtensionType) []Handler
}
RegistryPort defines the extension registry access port Used to decouple the engine from the global registry, supporting implementation replacement and test injection.
type RegistryStatus ¶
type RegistryStatus struct {
Timestamp time.Time
TotalExtensions int
RegisteredParsers int
RegisteredAnalyzers int
RegisteredHandlers int
CustomPlugins int
ExtensionDetails []ExtensionStatusDetail
LoadedExtensions []string
MissingParsers []string
MissingAnalyzers []string
}
RegistryStatus represents a registry status snapshot
type RequestGuard ¶
type RequestGuard struct {
// contains filtered or unexported fields
}
func NewRequestGuard ¶
func NewRequestGuard(policy *DefensePolicy) *RequestGuard
NewRequestGuard creates a request guard
func (*RequestGuard) ValidateRequest ¶
func (rg *RequestGuard) ValidateRequest(data []byte) error
ValidateRequest validates a request
Performs four-layer defense checks (in order): 1. Rate limiting - prevents traffic flooding 2. Size check - prevents oversized requests 3. Timeout check - prevents indefinite waiting 4. Data validation - prevents malformed and malicious input
All failures are recorded in the audit log
type ResourceMonitor ¶
type ResourceMonitor struct {
// contains filtered or unexported fields
}
ResourceMonitor monitors resource usage
func NewResourceMonitor ¶
func NewResourceMonitor(maxMemoryMB int, maxGoroutines int, maxTimeoutSec int) *ResourceMonitor
NewResourceMonitor creates a resource monitor
func (*ResourceMonitor) CheckMemory ¶
func (rm *ResourceMonitor) CheckMemory(size int64, label string) error
CheckMemory checks memory usage
func (*ResourceMonitor) CheckTimeout ¶
func (rm *ResourceMonitor) CheckTimeout() error
CheckTimeout checks for timeout
func (*ResourceMonitor) GetMemoryUsage ¶
func (rm *ResourceMonitor) GetMemoryUsage() map[string]int64
GetMemoryUsage returns memory usage statistics
func (*ResourceMonitor) ReleaseMemory ¶
func (rm *ResourceMonitor) ReleaseMemory(size int64, label string)
ReleaseMemory releases memory
type RulesConfig ¶
type RulesConfig struct {
Metadata map[string]interface{} `json:"_metadata"`
Entropy *EntropyConfig `json:"entropy"`
ToolMarkers *ToolMarkersConfig `json:"tool_markers"`
HeadlessBrowserUA *HeadlessBrowserConfig `json:"headless_browser_ua"`
OSPlatformContradiction *OSPlatformConfig `json:"os_platform_contradiction"`
UAOSContradiction *UAOSConfig `json:"ua_os_contradiction"`
MobileScreenContradiction *MobileScreenConfig `json:"mobile_screen_contradiction"`
UAFeatureContradiction *UAFeatureConfig `json:"ua_feature_contradiction"`
Scoring *RulesScoringConfig `json:"scoring"`
}
RulesConfig is the top-level rules configuration structure After the unified configuration entry, this structure is maintained by the extension package.
func DefaultRulesConfig ¶
func DefaultRulesConfig() *RulesConfig
DefaultRulesConfig returns the default rules configuration
func LoadRulesConfig ¶
func LoadRulesConfig(path string) (*RulesConfig, error)
LoadRulesConfig loads rules configuration from a JSON file
func LoadRulesConfigByFilename ¶
func LoadRulesConfigByFilename(filename string) (*RulesConfig, error)
LoadRulesConfigByFilename finds and loads rules configuration by filename within the project
func (*RulesConfig) String ¶
func (c *RulesConfig) String() string
String returns the JSON string representation of the configuration
type RulesProvider ¶
type RulesProvider interface {
LoadRules(path string) (*RulesConfig, error)
LoadRulesByFilename(filename string) (*RulesConfig, error)
DefaultRules() *RulesConfig
}
RulesProvider is the rules configuration provider port
type RulesScoringConfig ¶
type RulesScoringConfig struct {
AnomalyWeights map[string]float64 `json:"anomaly_weights"`
RiskLevels map[string]RiskLevel `json:"risk_levels"`
}
RulesScoringConfig holds scoring configuration Uses RulesScoringConfig to avoid conflicts with identically named configuration structures in other modules.
type SecurityAuditor ¶
type SecurityAuditor struct {
// contains filtered or unexported fields
}
SecurityAuditor is the security auditor
func NewSecurityAuditor ¶
func NewSecurityAuditor(maxEvents int) *SecurityAuditor
NewSecurityAuditor creates a security auditor
func (*SecurityAuditor) ClearAuditLog ¶
func (sa *SecurityAuditor) ClearAuditLog()
ClearAuditLog clears the audit log
func (*SecurityAuditor) GetAuditLog ¶
func (sa *SecurityAuditor) GetAuditLog() []AuditEvent
GetAuditLog returns the audit log
func (*SecurityAuditor) RecordEvent ¶
func (sa *SecurityAuditor) RecordEvent(eventType, severity, message string, details map[string]interface{}) error
RecordEvent records an event
type SimpleLogger ¶
type SimpleLogger struct {
// contains filtered or unexported fields
}
SimpleLogger is a simple logger implementation
func NewSimpleLogger ¶
func NewSimpleLogger(name string) *SimpleLogger
NewSimpleLogger creates a simple logger
func (*SimpleLogger) Debug ¶
func (sl *SimpleLogger) Debug(msg string, args ...interface{})
Debug logs debug information
func (*SimpleLogger) Error ¶
func (sl *SimpleLogger) Error(msg string, err error, args ...interface{})
Error logs an error
func (*SimpleLogger) Fatal ¶
func (sl *SimpleLogger) Fatal(msg string, args ...interface{})
Fatal logs a fatal error
func (*SimpleLogger) Info ¶
func (sl *SimpleLogger) Info(msg string, args ...interface{})
Info logs information
func (*SimpleLogger) SetLevel ¶
func (sl *SimpleLogger) SetLevel(level int)
SetLevel sets the log level
func (*SimpleLogger) Warn ¶
func (sl *SimpleLogger) Warn(msg string, args ...interface{})
Warn logs a warning
type ToolMarkersConfig ¶
type ToolMarkersConfig struct {
Enabled bool `json:"enabled"`
Patterns []MarkerInfo `json:"patterns"`
Description string `json:"description"`
}
ToolMarkersConfig holds tool marker configuration
type Transform ¶
type Transform interface {
// Transform performs the transformation
// input: input data
// Returns: transformed data, error
Transform(input interface{}) (interface{}, error)
// GetName returns the transform name
GetName() string
// GetInputType returns the input type name
GetInputType() string
// GetOutputType returns the output type name
GetOutputType() string
}
Transform is the data transformation interface Used for chained transformations on extensions
func CreateTransform ¶
CreateTransform creates a transform instance
type TransformFactory ¶
type TransformFactory struct {
// contains filtered or unexported fields
}
TransformFactory is the transform factory
type TransformStage ¶
type TransformStage struct {
// contains filtered or unexported fields
}
TransformStage transforms extension data into standard format
func NewTransformStage ¶
func NewTransformStage(registry RegistryPort) *TransformStage
NewTransformStage creates a new TransformStage
func (*TransformStage) GetDependencies ¶
func (t *TransformStage) GetDependencies() []string
GetDependencies returns the required preceding stages
func (*TransformStage) GetName ¶
func (t *TransformStage) GetName() string
GetName returns the stage name
type UAFeatureConfig ¶
type UAFeatureConfig struct {
Enabled bool `json:"enabled"`
Rules []UAFeatureRule `json:"rules"`
Description string `json:"description"`
}
UAFeatureConfig holds UA/Feature contradiction configuration
type UAFeatureRule ¶
type UAFeatureRule struct {
UAContains string `json:"ua_contains"`
FeatureCannotSupport string `json:"feature_cannot_support"`
Severity string `json:"severity"`
}
UAFeatureRule represents a UA/Feature rule
type UAOSConfig ¶
type UAOSConfig struct {
Enabled bool `json:"enabled"`
Rules []UARuleOS `json:"rules"`
Description string `json:"description"`
}
UAOSConfig holds UA/OS contradiction configuration
type UARuleOS ¶
type UARuleOS struct {
UAContains string `json:"ua_contains"`
OSCannotContain string `json:"os_cannot_contain"`
Severity string `json:"severity"`
}
UARuleOS represents a UA/OS rule
type ValidationResult ¶
type ValidationResult struct {
Valid bool
Error error
Warnings []string
Details map[string]interface{}
CheckedAt time.Time
}
ValidationResult holds validation results
func ComprehensiveValidation ¶
func ComprehensiveValidation(data []byte, metadata *ExtensionMetadata, policy *DefensePolicy) *ValidationResult
ComprehensiveValidation performs comprehensive validation
type Validator ¶
type Validator interface {
// Validate validates data
// value: value to validate
// Returns: whether valid, error
Validate(value interface{}) (bool, error)
// GetName returns the validator name
GetName() string
}
Validator is the data validation interface Used for extension data validation
func CreateValidator ¶
CreateValidator creates a validator instance
type ValidatorConfig ¶
type ValidatorConfig struct {
// Max data size (bytes)
MaxDataSize int
// Whether to enable strict mode
StrictMode bool
// Whether to validate metadata
ValidateMetadata bool
// Whether to validate configuration
ValidateConfig bool
}
ValidatorConfig holds validator configuration
type ValidatorFactory ¶
type ValidatorFactory struct {
// contains filtered or unexported fields
}
ValidatorFactory is the validator factory